我有一个日期格式为“14/11/2012 4:26:10 PM”从MySQL查询中提取。PHP - TimeSpan From DateTime
我对PHP并不是很有经验,但是如何计算日期“Then”和“Now”之间的简单时间间隔?
并将其格式化为可读的字符串?例如......“1小时,5分钟前”。
我试图寻找一个解决方案,我发现了一个我认为可以工作但它没有考虑AM/PM,所以最终导致一个问题,当我将它转换为时间戳。有人有什么主意吗?
这就是我要做的,但这并不工作这么好:
$time = $row["NotificationSent"];
list($day, $month, $year, $hour, $minute) = split('[/ :]', $time);
$timestamp = mktime($hour, $minute,0, $month, $day, $year);
$j = TimeSince($timestamp);
的timesince功能,我发现离我使用谷歌是:
function TimeSince($original) // $original should be the original date and time in Unix format
{
// Common time periods as an array of arrays
$periods = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
);
$today = time();
$since = $today - $original; // Find the difference of time between now and the past
// Loop around the periods, starting with the biggest
for ($i = 0, $j = count($periods); $i < $j; $i++)
{
$seconds = $periods[$i][0];
$name = $periods[$i][1];
// Find the biggest whole period
if (($count = floor($since/$seconds)) != 0)
{
break;
}
}
$output = ($count == 1) ? '1 '.$name : "$count {$name}s";
if ($i + 1 < $j)
{
// Retrieving the second relevant period
$seconds2 = $periods[$i + 1][0];
$name2 = $periods[$i + 1][1];
// Only show it if it's greater than 0
if (($count2 = floor(($since - ($seconds * $count))/$seconds2)) != 0)
{
$output .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
}
}
return $output;
}
返回结果被格式化为我正在查找的内容,但给出的数字不正确。 “19/11/2012 2:48:53 PM”正在返回“1天,5小时”,但应该是“17小时,32分钟”
任何帮助表示赞赏。
[如何计算使用PHP的两个日期之间的差异?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using- php) – Blazemonger
'mktime'预计24小时格式,当你正在分割文本时,你省略了'PM',因此在50%的情况下预计12h的差异。 –
你可以分享sql查询吗?我想知道你是如何实际存储时间戳记在你的分区 – omercnet