Convert datetime into time ago
I need to convert DateTime into the year, month, days, hours, minutes, seconds ago like as yahoo question asked 5week ago, or 1 year ago or 1 month ago, my date is saved in the database like this: 2011-11-30 05:25:50
.
Now I want to show like year, month, days, hours, minutes and seconds in PHP like: how much year, how many months , days, hours, minutes, seconds
ago, but need only one time unit show like it will be year or days or hours or minutes or seconds.
I have searched about this but not understand how I can do this, I know there are many questions at this topic on Stack Overflow, maybe it is duplicate but I am unable to solve my issue.
Thanks in advance.
Assuming you mean relative to the present (if you don't, please clarify your question), you could use this:
$then = new DateTime('2011-11-30 05:25:50');
$now = new DateTime();
$delta = $now->diff($then);
$quantities = array(
'year' => $delta->y,
'month' => $delta->m,
'day' => $delta->d,
'hour' => $delta->h,
'minute' => $delta->i,
'second' => $delta->s);
$str = '';
foreach($quantities as $unit => $value) {
if($value == 0) continue;
$str .= $value . ' ' . $unit;
if($value != 1) {
$str .= 's';
}
$str .= ', ';
}
$str = $str == '' ? 'a moment ' : substr($str, 0, -2);
echo $str;
Output:
1 year, 9 months, 17 days, 14 hours, 31 minutes, 31 seconds
I've always used this function:
function when($datetime) {
define("SECOND", 1);
define("MINUTE", 60 * SECOND);
define("HOUR", 60 * MINUTE); define("DAY", 24 * HOUR);
define("MONTH", 30 * DAY); $delta = time() - strtotime($datetime);
// convert
if($delta < 1 * MINUTE) { return $delta == 1 ? "one second ago" : $delta." seconds ago"; }
if($delta < 2 * MINUTE) { return "a minute ago"; } if($delta < 45 * MINUTE) { return floor($delta / MINUTE)." minutes ago"; }
if($delta < 90 * MINUTE) { return "an hour ago"; } if($delta < 24 * HOUR) { return floor($delta / HOUR)." hours ago"; }
if($delta < 48 * HOUR) { return "yesterday"; } if($delta < 30 * DAY) { return floor($delta / DAY)." days ago"; }
if($delta < 12 * MONTH) { $months = floor($delta / DAY / 30); return $months <= 1 ? "one month ago" : $months." months ago"; }
else { $years = floor($delta / DAY / 365); return $years <= 1 ? "one year ago" : $years." years ago"; }
}
echo when(YOUR DATE HERE) will return the best format of relative time, which might be days, hours, or if it wasn't that long ago, even in seconds.
Try this: http://www.php.net/manual/en/function.strtotime.php
PHP has a nice function strtotime
all ready for your needs.
That'll give you a timestamp, then you can just do math from there from whatever date you are subtracting from.
链接地址: http://www.djcxy.com/p/10114.html上一篇: 精确计算两个日期之间的天数
下一篇: 将datetime转换为更早的时间