PHP如何查找自date时间以来的时间?

如何find自从date时间过去的时间,如2010-04-28 17:25:43 ,最终输出文本应该像xx Minutes Ago / xx Days Ago

大部分的答案似乎集中在从一个string转换为date的时间。 看来你主要是想把date变成“5天前”的格式,等等。对不对?

这是我如何去做这件事:

 $time = strtotime('2010-04-28 17:25:43'); echo 'event happened '.humanTiming($time).' ago'; 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':''); } } 

我没有testing过,但它应该工作。

结果看起来像

 event happened 4 days ago 

要么

 event happened 1 minute ago 

干杯

想要分享PHPfunction,从而在语法上正确地修改Facebook的人类可读的时间格式。

例:

 echo get_time_ago(strtotime('now')); 

结果:

不到1分钟前

 function get_time_ago($time_stamp) { $time_difference = strtotime('now') - $time_stamp; if ($time_difference >= 60 * 60 * 24 * 365.242199) { /* * 60 seconds/minute * 60 minutes/hour * 24 hours/day * 365.242199 days/year * This means that the time difference is 1 year or more */ return get_time_ago_string($time_stamp, 60 * 60 * 24 * 365.242199, 'year'); } elseif ($time_difference >= 60 * 60 * 24 * 30.4368499) { /* * 60 seconds/minute * 60 minutes/hour * 24 hours/day * 30.4368499 days/month * This means that the time difference is 1 month or more */ return get_time_ago_string($time_stamp, 60 * 60 * 24 * 30.4368499, 'month'); } elseif ($time_difference >= 60 * 60 * 24 * 7) { /* * 60 seconds/minute * 60 minutes/hour * 24 hours/day * 7 days/week * This means that the time difference is 1 week or more */ return get_time_ago_string($time_stamp, 60 * 60 * 24 * 7, 'week'); } elseif ($time_difference >= 60 * 60 * 24) { /* * 60 seconds/minute * 60 minutes/hour * 24 hours/day * This means that the time difference is 1 day or more */ return get_time_ago_string($time_stamp, 60 * 60 * 24, 'day'); } elseif ($time_difference >= 60 * 60) { /* * 60 seconds/minute * 60 minutes/hour * This means that the time difference is 1 hour or more */ return get_time_ago_string($time_stamp, 60 * 60, 'hour'); } else { /* * 60 seconds/minute * This means that the time difference is a matter of minutes */ return get_time_ago_string($time_stamp, 60, 'minute'); } } function get_time_ago_string($time_stamp, $divisor, $time_unit) { $time_difference = strtotime("now") - $time_stamp; $time_units = floor($time_difference / $divisor); settype($time_units, 'string'); if ($time_units === '0') { return 'less than 1 ' . $time_unit . ' ago'; } elseif ($time_units === '1') { return '1 ' . $time_unit . ' ago'; } else { /* * More than "1" $time_unit. This is the "plural" message. */ // TODO: This pluralizes the time unit, which is done by adding "s" at the end; this will not work for i18n! return $time_units . ' ' . $time_unit . 's ago'; } } 

我觉得我有一个function,应该做你想要的:

 function time2string($timeline) { $periods = array('day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1); foreach($periods AS $name => $seconds){ $num = floor($timeline / $seconds); $timeline -= ($num * $seconds); $ret .= $num.' '.$name.(($num > 1) ? 's' : '').' '; } return trim($ret); } 

简单地把它应用到time()strtotime('2010-04-28 17:25:43')之间的区别如下:

 print time2string(time()-strtotime('2010-04-28 17:25:43')).' ago'; 

如果你使用php的Datetime类,你可以使用:

 function time_ago(Datetime $date) { $time_ago = ''; $diff = $date->diff(new Datetime('now')); if (($t = $diff->format("%m")) > 0) $time_ago = $t . ' months'; else if (($t = $diff->format("%d")) > 0) $time_ago = $t . ' days'; else if (($t = $diff->format("%H")) > 0) $time_ago = $t . ' hours'; else $time_ago = 'minutes'; return $time_ago . ' ago (' . $date->format('M j, Y') . ')'; } 

需要警告的是,大部分math计算的例子都有2038-01-18date的硬限制,并且不适用于虚构的date。

由于缺less基于DateTimeDateInterval的示例,因此我想提供一个满足OP需求的多用途函数,而另一些函数需要复杂的经过时间,比如1 month 2 days ago 。 还有其他一些用例,例如限制显示date而不是stream逝的时间,或者过滤部分已用时间结果。

另外,大部分例子假设已经过去了,从当前时间开始,下面的函数允许它被覆盖所需的结束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 = 'Ym-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; } 

有一点需要注意 – 所提供的filter值的检索间隔不会延续到下一个周期。 filter仅显示所提供周期的结果值,不重新计算周期以仅显示所需的filter总量。


用法

对于OP需要显示最高时段(截至2015年2月24日)。

 echo elapsedTimeString('2010-04-26'); /** 4 years ago */ 

要显示复合句点并提供一个自定义结束date(请注意缺乏时间和虚构的date)

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

显示过滤周期的结果(数组的sorting无关紧要)

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

如果达到限制,以所提供的格式显示开始date(默认Ymd)。

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

还有一堆其他用例。 它也可以很容易地适用于接受开始,结束或限制参数的unix时间戳和/或DateInterval对象。

我喜欢Mithun的代码,但是我稍微调整了一下,以便给出更合理的答案。

 function getTimeSince($eventTime) { $totaldelay = time() - strtotime($eventTime); if($totaldelay <= 0) { return ''; } else { $first = ''; $marker = 0; if($years=floor($totaldelay/31536000)) { $totaldelay = $totaldelay % 31536000; $plural = ''; if ($years > 1) $plural='s'; $interval = $years." year".$plural; $timesince = $timesince.$first.$interval; if ($marker) return $timesince; $marker = 1; $first = ", "; } if($months=floor($totaldelay/2628000)) { $totaldelay = $totaldelay % 2628000; $plural = ''; if ($months > 1) $plural='s'; $interval = $months." month".$plural; $timesince = $timesince.$first.$interval; if ($marker) return $timesince; $marker = 1; $first = ", "; } if($days=floor($totaldelay/86400)) { $totaldelay = $totaldelay % 86400; $plural = ''; if ($days > 1) $plural='s'; $interval = $days." day".$plural; $timesince = $timesince.$first.$interval; if ($marker) return $timesince; $marker = 1; $first = ", "; } if ($marker) return $timesince; if($hours=floor($totaldelay/3600)) { $totaldelay = $totaldelay % 3600; $plural = ''; if ($hours > 1) $plural='s'; $interval = $hours." hour".$plural; $timesince = $timesince.$first.$interval; if ($marker) return $timesince; $marker = 1; $first = ", "; } if($minutes=floor($totaldelay/60)) { $totaldelay = $totaldelay % 60; $plural = ''; if ($minutes > 1) $plural='s'; $interval = $minutes." minute".$plural; $timesince = $timesince.$first.$interval; if ($marker) return $timesince; $first = ", "; } if($seconds=floor($totaldelay/1)) { $totaldelay = $totaldelay % 1; $plural = ''; if ($seconds > 1) $plural='s'; $interval = $seconds." second".$plural; $timesince = $timesince.$first.$interval; } return $timesince; } } 

为了改善@arnorhs的答案,我已经增加了一个更精确的结果的能力,所以如果你想要几年,几个月,几天和几小时,因为用户join。

我已经添加了一个新参数,允许您指定您希望返回的精度点数。

 function get_friendly_time_ago($distant_timestamp, $max_units = 3) { $i = 0; $time = time() - $distant_timestamp; // to get the time since that moment $tokens = [ 31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second' ]; $responses = []; while ($i < $max_units) { foreach ($tokens as $unit => $text) { if ($time < $unit) { continue; } $i++; $numberOfUnits = floor($time / $unit); $responses[] = $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : ''); $time -= ($unit * $numberOfUnits); break; } } if (!empty($responses)) { return implode(', ', $responses) . ' ago'; } return 'Just now'; } 

一个可以与任何版本的PHP一起工作的选项是做已经build议的东西,就像这样:

 $eventTime = '2010-04-28 17:25:43'; $age = time() - strtotime($eventTime); 

那会在几秒钟内给你这个年龄。 从那里,你可以显示它,但是你希望。

但是,这种方法存在的一个问题是,它不考虑DST导致的时间转移。 如果这不是一个问题,那就去做吧。 否则,你可能会想在DateTime类中使用diff()方法 。 不幸的是,这只是一个选项,如果你至less在PHP 5.3。

使用这一个,你可以得到的

  $previousDate = '2013-7-26 17:01:10'; $startdate = new DateTime($previousDate); $endDate = new DateTime('now'); $interval = $endDate->diff($startdate); echo$interval->format('%y years, %m months, %d days'); 

参考这个http://ca2.php.net/manual/en/dateinterval.format.php

尝试这些回购之一:

https://github.com/salavert/time-ago-in-words

https://github.com/jimmiw/php-time-ago

我刚刚开始使用后者,做的伎俩,但没有stackoverflow风格的回退date有问题的date太远,也没有支持未来的date – 和API有点时髦,但至less它作品看起来完美无瑕,并保持…

将[saved_date]转换为时间戳。 获取当前时间戳。

当前时间戳 – [saved_date]时间戳。

那么你可以用date()来格式化它;

通常可以使用strtotime()函数将大多数date格式转换为时间戳。

为了找出时间stream逝,我通常使用time()而不是date()和格式化的时间戳。 然后得到后面的值和较早的值之间的差异并相应地格式化。 time()不同于date()的替代,但是在计算经过时间时它是完全有帮助的。

例:

time()的值看起来像这样1274467343增加一次。 因此,您可以使用值为1274467343 $erlierTime和值为1274467343 $latterTime ,然后执行$latterTime - $erlierTime以获得以秒为单位的时间。

写我自己的

 function getElapsedTime($eventTime) { $totaldelay = time() - strtotime($eventTime); if($totaldelay <= 0) { return ''; } else { if($days=floor($totaldelay/86400)) { $totaldelay = $totaldelay % 86400; return $days.' days ago.'; } if($hours=floor($totaldelay/3600)) { $totaldelay = $totaldelay % 3600; return $hours.' hours ago.'; } if($minutes=floor($totaldelay/60)) { $totaldelay = $totaldelay % 60; return $minutes.' minutes ago.'; } if($seconds=floor($totaldelay/1)) { $totaldelay = $totaldelay % 1; return $seconds.' seconds ago.'; } } } 

在这里,我使用自定义函数来查找自date时间以来的时间。


回声Datetodays('2013-7-26 17:01:10');

函数Datetodays($ d){

         $ date_start = $ d;
         $ date_end = date('Ymd H:i:s');

         define('SECOND',1);
         define('MINUTE',SECOND * 60);
         define('HOUR',MINUTE * 60);
         define('DAY',HOUR * 24);
         define('WEEK',DAY * 7);

         $ t1 = strtotime($ date_start);
         $ t2 = strtotime($ date_end);
         if($ t1> $ t2){
             $ diffrence = $ t1  -  $ t2;
         } else {
             $ diffrence = $ t2  -  $ t1;
         }

         //回声“ 
“$ DATE_END。” “$ DATE_START。” ” $ diffrence; $ results ['major'] = array(); //整数表示date时间关系中的较大数字 $ results1 = array(); $ string =''; $ results ['major'] ['weeks'] = floor($ diffrence / WEEK); $ results ['major'] ['days'] = floor($ diffrence / DAY); $ results ['major'] ['hours'] = floor($ diffrence / HOUR); $ results ['major'] ['minutes'] = floor($ diffrence / MINUTE); $ results ['major'] ['seconds'] = floor($ diffrence / SECOND); //的print_r($结果); //逻辑: //步骤1:取主要结果并将其转换为原始秒数(这将less于差值的秒数) // ex:$ result =($ results ['major'] ['weeks'] * WEEK) //步骤2:从差异(总时间)中减去较小的数字(结果) //例如:$ minor_result = $差异 - $结果 //第3步:在几秒钟内获得所需的时间并将其转换为次要格式 // ex:floor($ minor_result / DAY) $ results1 ['weeks'] = floor($ diffrence / WEEK); $ results1 ['days'] = floor((($ diffrence - ($ results ['major'] ['weeks'] * WEEK))/ DAY)); $ results1 ['hours'] = floor((($ diffrence - ($ results ['major'] ['days'] * DAY))/ HOUR)); $ results1 ['minutes'] = floor((($ diffrence - ($ results ['major'] ['hours'] * HOUR))/ MINUTE)); $ results1 ['seconds'] = floor((($ diffrence - ($ results ['major'] ['minutes'] * MINUTE))/ SECOND)); //的print_r($结果:1); if($ results1 ['weeks']!= 0 && $ results1 ['days'] == 0){ if($ results1 ['weeks'] == 1){ $ string = $ results1 ['weeks']。 ' 一周前'; } else { if($ results1 ['weeks'] == 2){ $ string = $ results1 ['weeks']。 ' 几周前'; } else { $ string ='2 weeks ago'; } } } elseif($ results1 ['weeks']!= 0 && $ results1 ['days']!= 0){ if($ results1 ['weeks'] == 1){ $ string = $ results1 ['weeks']。 ' 一周前'; } else { if($ results1 ['weeks'] == 2){ $ string = $ results1 ['weeks']。 ' 几周前'; } else { $ string ='2 weeks ago'; } } } elseif($ results1 ['weeks'] == 0 && $ results1 ['days']!= 0){ if($ results1 ['days'] == 1){ $ string = $ results1 ['days']。 “一天前”; } else { $ string = $ results1 ['days']。 ' 几天前'; } } elseif($ results1 ['days']!= 0 && $ results1 ['hours']!= 0){ $ string = $ results1 ['days']。 '天和'。 $ results1 ['小时']。 '小时前'; } elseif($ results1 ['days'] == 0 && $ results1 ['hours']!= 0){ if($ results1 ['hours'] == 1){ $ string = $ results1 ['hours']。 ' 一个小时前'; } else { $ string = $ results1 ['hours']。 '小时前'; } } elseif($ results1 ['hours']!= 0 && $ results1 ['minutes']!= 0){ $ string = $ results1 ['hours']。 '小时和'。 $ results1 ['分钟']。 ' 几分钟前'; } elseif($ results1 ['hours'] == 0 && $ results1 ['minutes']!= 0){ if($ results1 ['minutes'] == 1){ $ string = $ results1 ['minutes']。 '分钟前'; } else { $ string = $ results1 ['minutes']。 ' 几分钟前'; } } elseif($ results1 ['minutes']!= 0 && $ results1 ['seconds']!= 0){ $ string = $ results1 ['minutes']。 '分钟和'。 $ results1 ['秒']。 '秒前'; } elseif($ results1 ['minutes'] == 0 && $ results1 ['seconds']!= 0){ if($ results1 ['seconds'] == 1){ $ string = $ results1 ['seconds']。 '第二个以前'; } else { $ string = $ results1 ['seconds']。 '秒前'; } } 返回$ string; } ?>

你可以得到一个函数,直接形成WordPress的核心文件看看这里

http://core.trac.wordpress.org/browser/tags/3.6/wp-includes/formatting.php#L2121

 function human_time_diff( $from, $to = '' ) { if ( empty( $to ) ) $to = time(); $diff = (int) abs( $to - $from ); if ( $diff < HOUR_IN_SECONDS ) { $mins = round( $diff / MINUTE_IN_SECONDS ); if ( $mins <= 1 ) $mins = 1; /* translators: min=minute */ $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins ); } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) { $hours = round( $diff / HOUR_IN_SECONDS ); if ( $hours <= 1 ) $hours = 1; $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours ); } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) { $days = round( $diff / DAY_IN_SECONDS ); if ( $days <= 1 ) $days = 1; $since = sprintf( _n( '%s day', '%s days', $days ), $days ); } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) { $weeks = round( $diff / WEEK_IN_SECONDS ); if ( $weeks <= 1 ) $weeks = 1; $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks ); } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) { $months = round( $diff / ( 30 * DAY_IN_SECONDS ) ); if ( $months <= 1 ) $months = 1; $since = sprintf( _n( '%s month', '%s months', $months ), $months ); } elseif ( $diff >= YEAR_IN_SECONDS ) { $years = round( $diff / YEAR_IN_SECONDS ); if ( $years <= 1 ) $years = 1; $since = sprintf( _n( '%s year', '%s years', $years ), $years ); } return $since; } 

即兴创作对“人性化”function的作用。 它会计算一个“完全拉伸”的时间string翻译成人类可读的文本版本。 比如说像“1周2天1小时28分14秒”

 function humantime ($oldtime, $newtime = null, $returnarray = false) { if(!$newtime) $newtime = time(); $time = $newtime - $oldtime; // to get the time since that moment $tokens = array ( 31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second' ); $htarray = array(); foreach ($tokens as $unit => $text) { if ($time < $unit) continue; $numberOfUnits = floor($time / $unit); $htarray[$text] = $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':''); $time = $time - ( $unit * $numberOfUnits ); } if($returnarray) return $htarray; return implode(' ', $htarray); } 

不得不这样做最近 – 希望这可以帮助一个人。 它不能满足所有的可能性,但满足了我对一个项目的需求。

https://github.com/duncanheron/twitter_date_format

https://github.com/duncanheron/twitter_date_format/blob/master/twitter_date_format.php