Konwersja znacznika czasu na time ago w PHP np. 1 dzień, 2 dni temu…

Próbuję przekonwertować znacznik czasu formatu 2009-09-12 20:57:19 i przekształcić go w coś w rodzaju 3 minutes ago za pomocą PHP.

Znalazłem do tego przydatny skrypt, ale myślę, że szuka innego formatu do wykorzystania jako zmienna czasu. Skrypt, który chcę zmodyfikować do pracy z tym formatem to:

function _ago($tm,$rcs = 0) {
    $cur_tm = time(); 
    $dif = $cur_tm-$tm;
    $pds = array('second','minute','hour','day','week','month','year','decade');
    $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);

    for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
        $no = floor($no);
        if($no <> 1)
            $pds[$v] .='s';
        $x = sprintf("%d %s ",$no,$pds[$v]);
        if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0))
            $x .= time_ago($_tm);
        return $x;
    }

Myślę, że na tych kilku pierwszych linijkach skrypt próbuje zrobić coś, co wygląda tak (inny format daty):

$dif = 1252809479 - 2009-09-12 20:57:19;

Jak mam przerobić moje timestamp do tego (unix?) format?

 191
Author: lorem monkey, 2009-09-13

30 answers

Użyj przykładu:

echo time_elapsed_string('2013-05-01 00:22:35');
echo time_elapsed_string('@1367367755'); # timestamp input
echo time_elapsed_string('2013-05-01 00:22:35', true);

Wejście Może być dowolnym obsługiwanym formatem daty i czasu .

Wyjście:

4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago

Funkcja:

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
 354
Author: Glavić,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-15 14:46:53
function time_elapsed_string($ptime)
{
    $etime = time() - $ptime;

    if ($etime < 1)
    {
        return '0 seconds';
    }

    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  'minute',
                                 1  =>  'second'
                );
    $a_plural = array( 'year'   => 'years',
                       'month'  => 'months',
                       'day'    => 'days',
                       'hour'   => 'hours',
                       'minute' => 'minutes',
                       'second' => 'seconds'
                );

    foreach ($a as $secs => $str)
    {
        $d = $etime / $secs;
        if ($d >= 1)
        {
            $r = round($d);
            return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
        }
    }
}
 100
Author: Ayman Hussein,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-01 00:59:45
$time_elapsed = timeAgo($time_ago); //The argument $time_ago is in timestamp (Y-m-d H:i:s)format.

//Function definition

function timeAgo($time_ago)
{
    $time_ago = strtotime($time_ago);
    $cur_time   = time();
    $time_elapsed   = $cur_time - $time_ago;
    $seconds    = $time_elapsed ;
    $minutes    = round($time_elapsed / 60 );
    $hours      = round($time_elapsed / 3600);
    $days       = round($time_elapsed / 86400 );
    $weeks      = round($time_elapsed / 604800);
    $months     = round($time_elapsed / 2600640 );
    $years      = round($time_elapsed / 31207680 );
    // Seconds
    if($seconds <= 60){
        return "just now";
    }
    //Minutes
    else if($minutes <=60){
        if($minutes==1){
            return "one minute ago";
        }
        else{
            return "$minutes minutes ago";
        }
    }
    //Hours
    else if($hours <=24){
        if($hours==1){
            return "an hour ago";
        }else{
            return "$hours hrs ago";
        }
    }
    //Days
    else if($days <= 7){
        if($days==1){
            return "yesterday";
        }else{
            return "$days days ago";
        }
    }
    //Weeks
    else if($weeks <= 4.3){
        if($weeks==1){
            return "a week ago";
        }else{
            return "$weeks weeks ago";
        }
    }
    //Months
    else if($months <=12){
        if($months==1){
            return "a month ago";
        }else{
            return "$months months ago";
        }
    }
    //Years
    else{
        if($years==1){
            return "one year ago";
        }else{
            return "$years years ago";
        }
    }
}
 23
Author: Captain Red,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-23 17:00:15

Znalazłem lepsze rozwiązanie. Używa jQuery jednak działa doskonale. Również to odświeża się automatycznie podobnie jak tak i Facebook robi, więc nie musisz odświeżać strony, aby zobaczyć aktualizacje.

Ta wtyczka odczyta datetime attr w znaczniku <time> i wypełni go za Ciebie.

e.g. "4 minutes ago" or "about 1 day ago

Http://timeago.yarp.com/

 19
Author: Panama Jack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-19 07:52:00

Nie wiem, dlaczego nikt jeszcze nie wspomniał o węglu.

Https://github.com/briannesbitt/Carbon

Jest to rozszerzenie do PHP dateTime (które było już tutaj używane) i posiada metodę: diffForHumans. Więc wszystko co musisz zrobić to:

$dt = Carbon::parse('2012-9-5 23:26:11.123789');
echo $dt->diffForHumans();

Więcej przykładów: http://carbon.nesbot.com/docs/#api-humandiff

Zalety tego rozwiązania:

  • to działa na przyszłe daty i zwróci coś jak za 2 miesiące itp.
  • możesz użyć lokalizacja, aby uzyskać inne języki i pluralizacja działa dobrze
  • jeśli zaczniesz używać węgla do innych rzeczy praca z datami będzie tak prosta, jak nigdy.
 9
Author: Krzysztof Duszczyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-21 11:33:35
function humanTiming ($time)
        {

            $time = time() - $time; // to get the time since that moment
            $time = ($time<1)? 1 : $time;
            $tokens = array (
                31536000 => 'year',
                2592000 => 'month',
                604800 => 'week',
                86400 => 'day',
                3600 => 'hour',
                60 => 'minute',
                1 => 'second'
            );

            foreach ($tokens as $unit => $text) {
                if ($time < $unit) continue;
                $numberOfUnits = floor($time / $unit);
                return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
            }

        }

echo humanTiming( strtotime($mytimestring) );
 8
Author: brycejl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-30 00:15:02

Znalazłem wyniki takie jak:

1 lat, 2 miesięcy, 0 dni, 0 godzin, 53 minut i 1 sekund

Z tego powodu zrozumiałem funkcję, która szanuje liczby mnogie, usuwa puste wartości i opcjonalnie można skrócić wyjście:

function since($timestamp, $level=6) {
    global $lang;
    $date = new DateTime();
    $date->setTimestamp($timestamp);
    $date = $date->diff(new DateTime());
    // build array
    $since = json_decode($date->format('{"year":%y,"month":%m,"day":%d,"hour":%h,"minute":%i,"second":%s}'), true);
    // remove empty date values
    $since = array_filter($since);
    // output only the first x date values
    $since = array_slice($since, 0, $level);
    // build string
    $last_key = key(array_slice($since, -1, 1, true));
    $string = '';
    foreach ($since as $key => $val) {
        // separator
        if ($string) {
            $string .= $key != $last_key ? ', ' : ' ' . $lang['and'] . ' ';
        }
        // set plural
        $key .= $val > 1 ? 's' : '';
        // add date value
        $string .= $val . ' ' . $lang[ $key ];
    }
    return $string;
}

Wygląda znacznie lepiej:

1 rok, 2 miesiące, 53 minuty i 1 sekundę

Opcjonalnie użyj $level = 2, aby skrócić go w następujący sposób:

1 rok i 2 miesiące

Usuń część $lang jeśli potrzebujesz go tylko w języku angielskim lub zmodyfikuj to tłumaczenie, aby pasowało do Twoich potrzeb:

$lang = array(
    'second' => 'Sekunde',
    'seconds' => 'Sekunden',
    'minute' => 'Minute',
    'minutes' => 'Minuten',
    'hour' => 'Stunde',
    'hours' => 'Stunden',
    'day' => 'Tag',
    'days' => 'Tage',
    'month' => 'Monat',
    'months' => 'Monate',
    'year' => 'Jahr',
    'years' => 'Jahre',
    'and' => 'und',
);
 7
Author: mgutt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-03 11:27:19

Zmodyfikowałem trochę oryginalną funkcję, aby była (moim zdaniem bardziej użyteczna, lub logiczna).

// display "X time" ago, $rcs is precision depth
function time_ago ($tm, $rcs = 0) {
  $cur_tm = time(); 
  $dif = $cur_tm - $tm;
  $pds = array('second','minute','hour','day','week','month','year','decade');
  $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);

  for ($v = count($lngh) - 1; ($v >= 0) && (($no = $dif / $lngh[$v]) <= 1); $v--);
    if ($v < 0)
      $v = 0;
  $_tm = $cur_tm - ($dif % $lngh[$v]);

  $no = ($rcs ? floor($no) : round($no)); // if last denomination, round

  if ($no != 1)
    $pds[$v] .= 's';
  $x = $no . ' ' . $pds[$v];

  if (($rcs > 0) && ($v >= 1))
    $x .= ' ' . $this->time_ago($_tm, $rcs - 1);

  return $x;
}
 5
Author: Bobb Fwed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-17 18:09:23

Tylko dorzucić inną opcję...

Chociaż preferuję metodę DateTime tutaj, nie podobało mi się to, że wyświetlała 0 lat itp.

/* 
 * Returns a string stating how long ago this happened
 */

private function timeElapsedString($ptime){
    $diff = time() - $ptime;
    $calc_times = array();
    $timeleft   = array();

    // Prepare array, depending on the output we want to get.
    $calc_times[] = array('Year',   'Years',   31557600);
    $calc_times[] = array('Month',  'Months',  2592000);
    $calc_times[] = array('Day',    'Days',    86400);
    $calc_times[] = array('Hour',   'Hours',   3600);
    $calc_times[] = array('Minute', 'Minutes', 60);
    $calc_times[] = array('Second', 'Seconds', 1);

    foreach ($calc_times AS $timedata){
        list($time_sing, $time_plur, $offset) = $timedata;

        if ($diff >= $offset){
            $left = floor($diff / $offset);
            $diff -= ($left * $offset);
            $timeleft[] = "{$left} " . ($left == 1 ? $time_sing : $time_plur);
        }
    }

    return $timeleft ? (time() > $ptime ? null : '-') . implode(' ', $timeleft) : 0;
}
 4
Author: TMH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:04

Zrobiłem to i działa dobrze działa zarówno dla Unix timestamp jak {[1] } lub sformatowany czas jak 16-08-11 14:53:30

function timeAgo($time_ago) {
    $time_ago =  strtotime($time_ago) ? strtotime($time_ago) : $time_ago;
    $time  = time() - $time_ago;

switch($time):
// seconds
case $time <= 60;
return 'lessthan a minute ago';
// minutes
case $time >= 60 && $time < 3600;
return (round($time/60) == 1) ? 'a minute' : round($time/60).' minutes ago';
// hours
case $time >= 3600 && $time < 86400;
return (round($time/3600) == 1) ? 'a hour ago' : round($time/3600).' hours ago';
// days
case $time >= 86400 && $time < 604800;
return (round($time/86400) == 1) ? 'a day ago' : round($time/86400).' days ago';
// weeks
case $time >= 604800 && $time < 2600640;
return (round($time/604800) == 1) ? 'a week ago' : round($time/604800).' weeks ago';
// months
case $time >= 2600640 && $time < 31207680;
return (round($time/2600640) == 1) ? 'a month ago' : round($time/2600640).' months ago';
// years
case $time >= 31207680;
return (round($time/31207680) == 1) ? 'a year ago' : round($time/31207680).' years ago' ;

endswitch;
}

?>
 4
Author: Ahmad ghoneim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-11 12:54:32

It help you check it

   function calculate_time_span($seconds)
{  
 $year = floor($seconds /31556926);
$months = floor($seconds /2629743);
$week=floor($seconds /604800);
$day = floor($seconds /86400); 
$hours = floor($seconds / 3600);
 $mins = floor(($seconds - ($hours*3600)) / 60); 
$secs = floor($seconds % 60);
 if($seconds < 60) $time = $secs." seconds ago";
 else if($seconds < 3600 ) $time =($mins==1)?$mins."now":$mins." mins ago";
 else if($seconds < 86400) $time = ($hours==1)?$hours." hour ago":$hours." hours ago";
 else if($seconds < 604800) $time = ($day==1)?$day." day ago":$day." days ago";
 else if($seconds < 2629743) $time = ($week==1)?$week." week ago":$week." weeks ago";
 else if($seconds < 31556926) $time =($months==1)? $months." month ago":$months." months ago";
 else $time = ($year==1)? $year." year ago":$year." years ago";
return $time; 
}  
  $seconds = time() - strtotime($post->post_date); 
echo calculate_time_span($seconds); 
 2
Author: Abbbas khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-26 14:58:57

Wiem, że jest tu kilka odpowiedzi, ale oto, co wymyśliłem. Obsługuje tylko wartości DateTime MySQL zgodnie z oryginalnym pytaniem, na które odpowiadałem. Tablica $a wymaga trochę pracy. Z zadowoleniem przyjmuję uwagi na temat tego, jak poprawić. Wywołanie jako:

Echo time_elapsed_string('2014-11-14 09:42:28');

function time_elapsed_string($ptime)
{
    // Past time as MySQL DATETIME value
    $ptime = strtotime($ptime);

    // Current time as MySQL DATETIME value
    $csqltime = date('Y-m-d H:i:s');

    // Current time as Unix timestamp
    $ctime = strtotime($csqltime); 

    // Elapsed time
    $etime = $ctime - $ptime;

    // If no elapsed time, return 0
    if ($etime < 1){
        return '0 seconds';
    }

    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  'minute',
                                 1  =>  'second'
    );

    $a_plural = array( 'year'   => 'years',
                       'month'  => 'months',
                       'day'    => 'days',
                       'hour'   => 'hours',
                       'minute' => 'minutes',
                       'second' => 'seconds'
    );

    foreach ($a as $secs => $str){
        // Divide elapsed time by seconds
        $d = $etime / $secs;
        if ($d >= 1){
            // Round to the next lowest integer 
            $r = floor($d);
            // Calculate time to remove from elapsed time
            $rtime = $r * $secs;
            // Recalculate and store elapsed time for next loop
            if(($etime - $rtime)  < 0){
                $etime -= ($r - 1) * $secs;
            }
            else{
                $etime -= $rtime;
            }
            // Create string to return
            $estring = $estring . $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ';
        }
    }
    return $estring . ' ago';
}
 1
Author: rdpcoder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-14 20:38:01

Próbowałem tego i działa dobrze dla mnie

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-10');
$difference = $datetime1->diff($datetime2);
echo formatOutput($difference);

function formatOutput($diff){
    /* function to return the highrst defference fount */
    if(!is_object($diff)){
        return;
    }

    if($diff->y > 0){
        return $diff->y .(" year".($diff->y > 1?"s":"")." ago");
    }

    if($diff->m > 0){
        return $diff->m .(" month".($diff->m > 1?"s":"")." ago");
    }

    if($diff->d > 0){
        return $diff->d .(" day".($diff->d > 1?"s":"")." ago");
    }

    if($diff->h > 0){
        return $diff->h .(" hour".($diff->h > 1?"s":"")." ago");
    }

    if($diff->i > 0){
        return $diff->i .(" minute".($diff->i > 1?"s":"")." ago");
    }

    if($diff->s > 0){
        return $diff->s .(" second".($diff->s > 1?"s":"")." ago");
    }
}

Sprawdź ten link dla odniesienia tutaj

Dzięki! i baw się dobrze.
 1
Author: Ruberandinda Patience,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-24 09:14:14

Wiele rozwiązań tutaj nie uwzględniało zaokrąglania. Na przykład:

Zdarzenie miało miejsce o 15: 00 dwa dni temu. Jeśli sprawdzasz o 14: 00, pokaże się jeden dzień temu. Jeśli sprawdzasz o 16: 00 pokaże się dwa dni temu.

Jeśli pracujesz z czasem uniksowym, pomaga to:

// how long since event has passed in seconds
$secs = time() - $time_ago;

// how many seconds in a day
$sec_per_day = 60*60*24;

// days elapsed
$days_elapsed = floor($secs / $sec_per_day);

// how many seconds passed today
$today_seconds = date('G')*3600 + date('i') * 60 + date('s');

// how many seconds passed in the final day calculation
$remain_seconds = $secs % $sec_per_day;

if($today_seconds < $remain_seconds)
{
    $days_elapsed++;
}

echo 'The event was '.$days_ago.' days ago.';

To nie jest idealne, jeśli martwisz się o sekundy przestępne i czas letni.

 1
Author: Frank Forte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-19 17:02:27

Będziesz musiał wziąć każdy kawałek znacznika czasu i przekonwertować go na czas uniksowy. 2009-09-12 20:57:19

(((2008-1970)*365)+(8*30)+12)*24+20 da ci przybliżoną liczbę godzin od 1 stycznia 1970 roku.

Weź tę liczbę, pomnóż przez 60 i dodaj 57, aby uzyskać minuty.

Weź to, pomnóż przez 60 i dodaj 19.

To by ją jednak bardzo zgrubnie i niedokładnie przekonwertowało.

Czy Jest jakiś powód, dla którego nie można po prostu wziąć normalny czas Unix na początek?

 0
Author: LukeWarm74,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-09-13 02:45:20

Jeśli używasz MySQL, użyj UNIX_TIMESTAMP() funkcja.

 0
Author: CpnCrunch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-29 18:20:44

Ta funkcja nie jest przeznaczona do użycia w języku angielskim. Przetłumaczyłem słowa na angielski. Wymaga to więcej poprawek przed użyciem w języku angielskim.

function ago($d) {
$ts = time() - strtotime(str_replace("-","/",$d));

        if($ts>315360000) $val = round($ts/31536000,0).' year';
        else if($ts>94608000) $val = round($ts/31536000,0).' years';
        else if($ts>63072000) $val = ' two years';
        else if($ts>31536000) $val = ' a year';

        else if($ts>24192000) $val = round($ts/2419200,0).' month';
        else if($ts>7257600) $val = round($ts/2419200,0).' months';
        else if($ts>4838400) $val = ' two months';
        else if($ts>2419200) $val = ' a month';


        else if($ts>6048000) $val = round($ts/604800,0).' week';
        else if($ts>1814400) $val = round($ts/604800,0).' weeks';
        else if($ts>1209600) $val = ' two weeks';
        else if($ts>604800) $val = ' a week';

        else if($ts>864000) $val = round($ts/86400,0).' day';
        else if($ts>259200) $val = round($ts/86400,0).' days';
        else if($ts>172800) $val = ' two days';
        else if($ts>86400) $val = ' a day';

        else if($ts>36000) $val = round($ts/3600,0).' year';
        else if($ts>10800) $val = round($ts/3600,0).' years';
        else if($ts>7200) $val = ' two years';
        else if($ts>3600) $val = ' a year';

        else if($ts>600) $val = round($ts/60,0).' minute';
        else if($ts>180) $val = round($ts/60,0).' minutes';
        else if($ts>120) $val = ' two minutes';
        else if($ts>60) $val = ' a minute';

        else if($ts>10) $val = round($ts,0).' second';
        else if($ts>2) $val = round($ts,0).' seconds';
        else if($ts>1) $val = ' two seconds';
        else $val = $ts.' a second';


        return $val;
    }
 0
Author: shnisaka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-16 20:27:34

Lekko zmodyfikowana odpowiedź z góry:

  $commentTime = strtotime($whatever)
  $today       = strtotime('today');
  $yesterday   = strtotime('yesterday');
  $todaysHours = strtotime('now') - strtotime('today');

private function timeElapsedString(
    $commentTime,
    $todaysHours,
    $today,
    $yesterday
) {
    $tokens = array(
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    $time = time() - $commentTime;
    $time = ($time < 1) ? 1 : $time;
    if ($commentTime >= $today || $commentTime < $yesterday) {
        foreach ($tokens as $unit => $text) {
            if ($time < $unit) {
                continue;
            }
            if ($text == 'day') {
                $numberOfUnits = floor(($time - $todaysHours) / $unit) + 1;
            } else {
                $numberOfUnits = floor(($time)/ $unit);
            }
            return $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '') . ' ago';
        }
    } else {
        return 'Yesterday';
    }
}
 0
Author: Mr Sorbose,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-28 14:12:19

/ Align = "left" / Jest to zmodyfikowana wersja postu Abbbasa Khana:

<?php

  function calculate_time_span($post_time)
  {  
  $seconds = time() - strtotime($post);
  $year = floor($seconds /31556926);
  $months = floor($seconds /2629743);
  $week=floor($seconds /604800);
  $day = floor($seconds /86400); 
  $hours = floor($seconds / 3600);
  $mins = floor(($seconds - ($hours*3600)) / 60); 
  $secs = floor($seconds % 60);
  if($seconds < 60) $time = $secs." seconds ago";
  else if($seconds < 3600 ) $time =($mins==1)?$mins."now":$mins." mins ago";
  else if($seconds < 86400) $time = ($hours==1)?$hours." hour ago":$hours." hours ago";
  else if($seconds < 604800) $time = ($day==1)?$day." day ago":$day." days ago";
  else if($seconds < 2629743) $time = ($week==1)?$week." week ago":$week." weeks ago";
  else if($seconds < 31556926) $time =($months==1)? $months." month ago":$months." months ago";
  else $time = ($year==1)? $year." year ago":$year." years ago";
  return $time; 
  }  



 // uses
 // $post_time="2017-12-05 02:05:12";
 // echo calculate_time_span($post_time); 
 0
Author: drtechno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-05 18:23:13

Kiedy rozwijamy system wiadomości lub powiadomień w naszej aplikacji, gdzie musisz pokazać czas jak "1 godzina temu", lub 2 tygodnie temu itp. Jest to po prostu obliczanie czasu od bieżącego do czasu post wiadomości

Odpowiadam tutaj na wcześniej zadane pytanie na tej stronie XX czas temu funkcja nie działa

Mam nadzieję, że to będzie pomocne dla ciebie

 0
Author: vinay chaubey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-26 05:26:04
$time_ago = ' ';
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',2592000 => 'month',604800 => 'week',86400 => 'day',3600 => 'hour',
60  => 'minute',1 => 'second');
foreach ($tokens as $unit => $text) {
if ($time < $unit)continue;
$numberOfUnits = floor($time / $unit);
$time_ago = ' '.$time_ago. $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').'  ';
$time = $time % $unit;}echo $time_ago;
 -1
Author: Mehreen Jamil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-18 09:53:50

Oto moje rozwiązanie proszę sprawdzić i zmodyfikować zgodnie z wymaganiami

function getHowLongAgo($date, $display = array('Year', 'Month', 'Day', 'Hour', 'Minute', 'Second'), $ago = '') {
        date_default_timezone_set('Australia/Sydney');
        $timestamp = strtotime($date);
        $timestamp = (int) $timestamp;
        $current_time = time();
        $diff = $current_time - $timestamp;

        //intervals in seconds
        $intervals = array(
            'year' => 31556926, 'month' => 2629744, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute' => 60
        );

        //now we just find the difference
        if ($diff == 0) {
            return ' Just now ';
        }

        if ($diff < 60) {
            return $diff == 1 ? $diff . ' second ago ' : $diff . ' seconds ago ';
        }

        if ($diff >= 60 && $diff < $intervals['hour']) {
            $diff = floor($diff / $intervals['minute']);
            return $diff == 1 ? $diff . ' minute ago ' : $diff . ' minutes ago ';
        }

        if ($diff >= $intervals['hour'] && $diff < $intervals['day']) {
            $diff = floor($diff / $intervals['hour']);
            return $diff == 1 ? $diff . ' hour ago ' : $diff . ' hours ago ';
        }

        if ($diff >= $intervals['day'] && $diff < $intervals['week']) {
            $diff = floor($diff / $intervals['day']);
            return $diff == 1 ? $diff . ' day ago ' : $diff . ' days ago ';
        }

        if ($diff >= $intervals['week'] && $diff < $intervals['month']) {
            $diff = floor($diff / $intervals['week']);
            return $diff == 1 ? $diff . ' week ago ' : $diff . ' weeks ago ';
        }

        if ($diff >= $intervals['month'] && $diff < $intervals['year']) {
            $diff = floor($diff / $intervals['month']);
            return $diff == 1 ? $diff . ' month ago ' : $diff . ' months ago ';
        }

        if ($diff >= $intervals['year']) {
            $diff = floor($diff / $intervals['year']);
            return $diff == 1 ? $diff . ' year ago ' : $diff . ' years ago ';
        }
    }

Thanks

 -1
Author: Dineshaws,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-09 13:08:43
# This function prints the difference between two php datetime objects
# in a more human readable form
# inputs should be like strtotime($date)
function humanizeDateDiffference($now,$otherDate=null,$offset=null){
    if($otherDate != null){
        $offset = $now - $otherDate;
    }
    if($offset != null){
        $deltaS = $offset%60;
        $offset /= 60;
        $deltaM = $offset%60;
        $offset /= 60;
        $deltaH = $offset%24;
        $offset /= 24;
        $deltaD = ($offset > 1)?ceil($offset):$offset;      
    } else{
        throw new Exception("Must supply otherdate or offset (from now)");
    }
    if($deltaD > 1){
        if($deltaD > 365){
            $years = ceil($deltaD/365);
            if($years ==1){
                return "last year"; 
            } else{
                return "<br>$years years ago";
            }   
        }
        if($deltaD > 6){
            return date('d-M',strtotime("$deltaD days ago"));
        }       
        return "$deltaD days ago";
    }
    if($deltaD == 1){
        return "Yesterday";
    }
    if($deltaH == 1){
        return "last hour";
    }
    if($deltaM == 1){
        return "last minute";
    }
    if($deltaH > 0){
        return $deltaH." hours ago";
    }
    if($deltaM > 0){
        return $deltaM." minutes ago";
    }
    else{
        return "few seconds ago";
    }
}
 -1
Author: Ramesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-17 13:01:57

Użycie:

echo elapsed_time('2016-05-09 17:00:00'); // 18 saat 8 dakika önce yazıldı.

Funkcja:

function elapsed_time($time){// Nekadar zaman geçmiş

        $diff = time() - strtotime($time); 

        $sec = $diff;
        $min = floor($diff/60);
        $hour = floor($diff/(60*60));
        $hour_min = floor($min - ($hour*60));
        $day = floor($diff/(60*60*24));
        $day_hour = floor($hour - ($day*24));
        $week = floor($diff/(60*60*24*7));
        $mon = floor($diff/(60*60*24*7*4));
        $year = floor($diff/(60*60*24*7*4*12));

        //difference calculate to string
        if($sec < (60*5)){
            return 'şimdi yazıldı.';
        }elseif($min < 60){
            return 'biraz önce yazıldı.';
        }elseif($hour < 24){
            return $hour.' saat '.$hour_min.' dakika önce yazıldı.';
        }elseif($day < 7){
            if($day_hour!=0){$day_hour=$day_hour.' saat ';}else{$day_hour='';}
            return $day.' gün '.$day_hour.'önce yazıldı.';
        }elseif($week < 4){
            return $week.' hafta önce yazıldı.';
        }elseif($mon < 12){
            return $mon.' ay önce yazıldı.';
        }else{
            return $year.' yıl önce yazıldı.';
        }
    }
 -1
Author: Limitless isa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-10 08:23:42

Yo można użyć:

date("Y-m-d H:i:s",strtotime("1 day ago"));
 -2
Author: William Wong Garay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-12 18:19:34

Poniżej przedstawiamy bardzo proste i niezwykle efektywne rozwiązanie.

function timeElapsed($originalTime){

        $timeElapsed=time()-$originalTime;

        /*
          You can change the values of the following 2 variables 
          based on your opinion. For 100% accuracy, you can call
          php's cal_days_in_month() and do some additional coding
          using the values you get for each month. After all the
          coding, your final answer will be approximately equal to
          mine. That is why it is okay to simply use the average
          values below.
        */
        $averageNumbDaysPerMonth=(365.242/12);
        $averageNumbWeeksPerMonth=($averageNumbDaysPerMonth/7);

        $time1=(((($timeElapsed/60)/60)/24)/365.242);
        $time2=floor($time1);//Years
        $time3=($time1-$time2)*(365.242);
        $time4=($time3/$averageNumbDaysPerMonth);
        $time5=floor($time4);//Months
        $time6=($time4-$time5)*$averageNumbWeeksPerMonth;
        $time7=floor($time6);//Weeks
        $time8=($time6-$time7)*7;
        $time9=floor($time8);//Days
        $time10=($time8-$time9)*24;
        $time11=floor($time10);//Hours
        $time12=($time10-$time11)*60;
        $time13=floor($time12);//Minutes
        $time14=($time12-$time13)*60;
        $time15=round($time14);//Seconds

        $timeElapsed=$time2 . 'yrs ' . $time5 . 'months ' . $time7 . 
                     'weeks ' . $time9 .  'days ' . $time11 . 'hrs '
                     . $time13 . 'mins and ' . $time15 . 'secs.';

        return $timeElapsed;

}

Echo timeElapsed(1201570814);

Przykładowe wyjście:

6 lat 4 miesiące 3 tygodnie 4 dni 12 godzin 40 minut i 36 sekund.

 -2
Author: user3008679,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-24 20:00:52

Oto moje rozwiązanie dla modułu powiadomień, który zbudowałem jakiś czas temu. Zwraca wyjście podobne do listy rozwijanej powiadomień Facebook (np. 1 dzień temu, przed chwilą itp.).

public function getTimeDifference($time) {
    //Let's set the current time
    $currentTime = date('Y-m-d H:i:s');
    $toTime = strtotime($currentTime);

    //And the time the notification was set
    $fromTime = strtotime($time);

    //Now calc the difference between the two
    $timeDiff = floor(abs($toTime - $fromTime) / 60);

    //Now we need find out whether or not the time difference needs to be in
    //minutes, hours, or days
    if ($timeDiff < 2) {
        $timeDiff = "Just now";
    } elseif ($timeDiff > 2 && $timeDiff < 60) {
        $timeDiff = floor(abs($timeDiff)) . " minutes ago";
    } elseif ($timeDiff > 60 && $timeDiff < 120) {
        $timeDiff = floor(abs($timeDiff / 60)) . " hour ago";
    } elseif ($timeDiff < 1440) {
        $timeDiff = floor(abs($timeDiff / 60)) . " hours ago";
    } elseif ($timeDiff > 1440 && $timeDiff < 2880) {
        $timeDiff = floor(abs($timeDiff / 1440)) . " day ago";
    } elseif ($timeDiff > 2880) {
        $timeDiff = floor(abs($timeDiff / 1440)) . " days ago";
    }

    return $timeDiff;
}
 -2
Author: Ciaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-04 12:42:56

po prostu podaj datę do tego func. to by wydrukować w formacie czasu temu dla ciebie

date_default_timezone_set('your-time-zone');
function convert($datetime){
  $time=strtotime($datetime);
  $diff=time()-$time;
  $diff/=60;
  $var1=floor($diff);
  $var=$var1<=1 ? 'min' : 'mins';
  if($diff>=60){
    $diff/=60;
    $var1=floor($diff);
    $var=$var1<=1 ? 'hr' : 'hrs';
    if($diff>=24){$diff/=24;$var1=floor($diff);$var=$var1<=1 ? 'day' : 'days';
    if($diff>=30.4375){$diff/=30.4375;$var1=floor($diff);$var=$var1<=1 ? 'month' : 'months';
    if($diff>=12){$diff/=12;$var1=floor($diff);$var=$var1<=1 ? 'year' : 'years';}}}}
    echo $var1,' ',$var,' ago';
  }
 -2
Author: hrishi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-06 20:02:48

Oryginalnie napisane i dostępne pod tym linkiem

function _ago($tm,$rcs = 0) {
   $cur_tm = time(); $dif = $cur_tm-$tm;
   $pds = array('second','minute','hour','day','week','month','year','decade');
   $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
   for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);

   $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
   if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
   return $x;
}

Potrzebuje wartości time (), która powie Ci ile sekund / minut/godzin/dni/lat / dekad temu.

 -2
Author: Usman Shaukat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-10 15:42:42

Używam poniższej funkcji od kilku lat. I działa dobrze:

function timeDifference($timestamp)
{
    $otherDate=$timestamp;
    $now=@date("Y-m-d H:i:s");

    $secondDifference=@strtotime($now)-@strtotime($otherDate);
    $extra="";
    if ($secondDifference == 2592000) { 
    // months 
    $difference = $secondDifference/2592000; 
    $difference = round($difference,0); 
    if ($difference>1) { $extra="s"; } 
    $difference = $difference." month".$extra." ago"; 
}else if($secondDifference > 2592000)
    {$difference=timestamp($timestamp);} 
elseif ($secondDifference >= 604800) { 
    // weeks 
    $difference = $secondDifference/604800; 
    $difference = round($difference,0); 
    if ($difference>1) { $extra="s"; } 
    $difference = $difference." week".$extra." ago"; 
} 
elseif ($secondDifference >= 86400) { 
    // days 
    $difference = $secondDifference/86400; 
    $difference = round($difference,0); 
    if ($difference>1) { $extra="s"; } 
    $difference = $difference." day".$extra." ago"; 
} 
elseif ($secondDifference >= 3600) { 
    // hours 

    $difference = $secondDifference/3600; 
    $difference = round($difference,0); 
    if ($difference>1) { $extra="s"; } 
    $difference = $difference." hour".$extra." ago"; 
} 
elseif ($secondDifference < 3600) { 
    // hours 
    // for seconds (less than minute)
    if($secondDifference<=60)
    {       
        if($secondDifference==0)
        {
            $secondDifference=1;
        }
        if ($secondDifference>1) { $extra="s"; }
        $difference = $secondDifference." second".$extra." ago"; 

    }
    else
    {

$difference = $secondDifference/60; 
        if ($difference>1) { $extra="s"; }else{$extra="";}
        $difference = round($difference,0); 
        $difference = $difference." minute".$extra." ago"; 
    }
} 

$FinalDifference = $difference; 
return $FinalDifference;
}
 -3
Author: Ayyaz Zafar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-16 17:02:26