Hướng dẫn time_elapsed_string php

Be warned, the majority of the mathematically calculated examples have a hard limit of 2038-01-18 dates and will not work with fictional dates.

As there was a lack of DateTime and DateInterval based examples, I wanted to provide a multi-purpose function that satisfies the OP's need and others wanting compound elapsed periods, such as 1 month 2 days ago. Along with a bunch of other use cases, such as a limit to display the date instead of the elapsed time, or to filter out portions of the elapsed time result.

Additionally the majority of the examples assume elapsed is from the current time, where the below function allows for it to be overridden with the desired end date.

/**
 * multi-purpose function to calculate the time elapsed between $start and optional $end
 * @param string|null $start the date string to start calculation
 * @param string|null $end the date string to end calculation
 * @param string $suffix the suffix string to include in the calculated string
 * @param string $format the format of the resulting date if limit is reached or no periods were found
 * @param string $separator the separator between periods to use when filter is not true
 * @param null|string $limit date string to stop calculations on and display the date if reached - ex: 1 month
 * @param bool|array $filter false to display all periods, true to display first period matching the minimum, or array of periods to display ['year', 'month']
 * @param int $minimum the minimum value needed to include a period
 * @return string
 */
function elapsedTimeString[$start, $end = null, $limit = null, $filter = true, $suffix = 'ago', $format = 'Y-m-d', $separator = ' ', $minimum = 1]
{
    $dates = [object] array[
        'start' => new DateTime[$start ? : 'now'],
        'end' => new DateTime[$end ? : 'now'],
        'intervals' => array['y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second'],
        'periods' => array[]
    ];
    $elapsed = [object] array[
        'interval' => $dates->start->diff[$dates->end],
        'unknown' => 'unknown'
    ];
    if [$elapsed->interval->invert === 1] {
        return trim['0 seconds ' . $suffix];
    }
    if [false === empty[$limit]] {
        $dates->limit = new DateTime[$limit];
        if [date_create[]->add[$elapsed->interval] > $dates->limit] {
            return $dates->start->format[$format] ? : $elapsed->unknown;
        }
    }
    if [true === is_array[$filter]] {
        $dates->intervals = array_intersect[$dates->intervals, $filter];
        $filter = false;
    }
    foreach [$dates->intervals as $period => $name] {
        $value = $elapsed->interval->$period;
        if [$value >= $minimum] {
            $dates->periods[] = vsprintf['%1$s %2$s%3$s', array[$value, $name, [$value !== 1 ? 's' : '']]];
            if [true === $filter] {
                break;
            }
        }
    }
    if [false === empty[$dates->periods]] {
        return trim[vsprintf['%1$s %2$s', array[implode[$separator, $dates->periods], $suffix]]];
    }

    return $dates->start->format[$format] ? : $elapsed->unknown;
}

One thing to note - the retrieved intervals for the supplied filter values do not carry over to the next period. The filter merely displays the resulting value of the supplied periods and does not recalculate the periods to display only the desired filter total.

Usage

For the OP's need of displaying the highest period [as of 2015-02-24].

echo elapsedTimeString['2010-04-26'];
/** 4 years ago */

To display compound periods and supply a custom end date [note the lack of time supplied and fictional dates].

echo elapsedTimeString['1920-01-01', '2500-02-24', null, false];
/** 580 years 1 month 23 days ago */

To display the result of filtered periods [ordering of array doesn't matter].

echo elapsedTimeString['2010-05-26', '2012-02-24', null, ['month', 'year']];
/** 1 year 8 months ago */

To display the start date in the supplied format [default Y-m-d] if the limit is reached.

echo elapsedTimeString['2010-05-26', '2012-02-24', '1 year'];
/** 2010-05-26 */

There are bunch of other use cases. It can also easily be adapted to accept unix timestamps and/or DateInterval objects for the start, end, or limit arguments.

Hướng dẫn dùng abstract support trong PHP

Đã đăng vào thg 1 22, 2017 1:58 CH 1 phút đọc *Chào các bạn, * Hôm nay chúng ta cùng tìm hiểu về Abstract Class trong PHP nhé! I/ Abstract Class là gì ? Lớp trừu ...

Hướng dẫn dùng getscript trong PHP

Miêu tảPhương thức jQuery.getScript[url,[callback]] trong jQuery tải và thực thi một JavaScript file bởi sử dụng một HTTP GET request.Nó trả về đối tượng ...

Hướng dẫn dùng symfony form trong PHP

Đã đăng vào thg 4 14, 2020 2:38 CH 5 phút đọc Tuần vừa qua mình mới join vào dự án ec-cube là một cms xây dựng dựa trên symfony framework, trong bài viết này mình ...

Hướng dẫn dùng en.json trong PHP

Bài trước chúng ta đã tìm hiểu được khái niệm JSON là gì rồi và cũng biết được cấu trúc chuỗi JSON như thế nào, vậy thì trong bài này chúng ta sẽ tìm ...

Hướng dẫn dùng coder pfp trong PHP

Nội dungNội dung chínhBiến trong PHPKhai báo biến trong PHPCác biến trong PHP Đầu ra các biếnPHP là một ngôn ngữ định kiểu lỏng lẻoPhạm vi các biến trong ...

Hướng dẫn dùng arithmatics trong PHP

Trang chủTutorialsHọc PHP trong 7 ngàyTrong bất kỳ lĩnh vực nào chúng ta cũng phải tính toán, so sánh,... một cái gì đó. Lập trình thì cũng như vậy thôi. Và để ...

Hướng dẫn default argument in php

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right, before the function is actually called ...

Hướng dẫn dùng 400 php trong PHP

Nội dung chính2. Toán tử số học [Arithmetic Operator] trong PHP2. Toán tử gán [Assignment Operator] trong PHP3. Toán tử so sánh [Comparison Operator] trong PHP4. Các toán tử ...

Hướng dẫn dùng array yaml trong PHP

YAML là gì?YAML [YAML Ain’t Markup Language] là một chuẩn dữ liệu kiểu serialization dành cho tất cả các ngôn ngữ. Nó được sử dụng phổ biến để tạo ra các ...

Hướng dẫn dùng image0 jpg trong PHP

Tổng quan về kỹ thuật Upload file PHPTạo form HTML fileCode Php xử lý uploadCode Php xử lý upload nhiều fileTổng quan về kỹ thuật Upload file trong PHPĐể HTML FORM có ...

Hướng dẫn dùng debian latest trong PHP

PHP là ngôn ngữ lập trình phổ biến nhất thế giới và hiện nay PHP đã phát triển tới phiên bản 8.1 [tính ở thời điểm bài viết này]. Mình xin hướng dẫn ...

Hướng dẫn dùng image uoload trong PHP

Với mọi trang web đều phải có chức năng upload image lên đưa Database với mục đích thêm hình ảnh vào cơ sở dữ liệu MySQL. Bài viết này sẽ hướng dẫn bạn ...

Hướng dẫn count php

[PHP 4, PHP 5, PHP 7, PHP 8]count — Counts all elements in an array or in a Countable objectDescriptioncount[Countable|array $value, int $mode = COUNT_NORMAL]: intParameters value An array or ...

Hướng dẫn dùng creating png trong PHP

Tổng quan về kỹ thuật Upload file PHPTạo form HTML fileCode Php xử lý uploadCode Php xử lý upload nhiều fileTổng quan về kỹ thuật Upload file trong PHPĐể HTML FORM có ...

Hướng dẫn dùng echo flooring trong PHP

Vietnamese [Tiếng Việt] translation by Thai An [you can also view the original English article] Việc lấy thông tin từ một mảng thông tin đã được sắp xếp luôn dễ dàng ...

Hướng dẫn dùng stick pfp trong PHP

mjt at jpeto dot net ¶13 years ago I strongly recommend, that you use header[$_SERVER[SERVER_PROTOCOL]. 404 Not Found]; instead of header[HTTP/1.1 404 Not Found]; I had big troubles with ...

Hướng dẫn dùng unhash sha1 trong PHP

# DescriptionHàm sha1[] trong php có tác dụng chuyển một chuỗi sang một chuỗi mới đã được mã hóa theo tiêu chuẩn sha1.Trong php không có hàm nào hỗ trợ ...

Hướng dẫn php 8 isset

Hàm isset[] trong PHP mình cũng đã sử dụng khá nhiều lần trong series này rồi nhưng vẫn có một số bạn mail hỏi sự khác nhau giữa hàm isset[] và ...

Hướng dẫn dùng png interlaced trong PHP

Interlaced PNG là khái niệm phổ biến trong Photoshop. Tuy vậy, không phải ai cũng biết rõ bản chất của nó để có thể áp dụng trên thực tế. Vậy Interlaced PNG ...

Hướng dẫn dùng atan2 python trong PHP

❮ Tham khảo Toán PHPThí dụTrả về tiếp tuyến cung của hai biến bằng hàm atan2 []:

Chủ Đề