sli*_*khi 16 php strtotime microtime
我想在两个日期时间字符串之间传递时间(包括毫秒)
例:
$pageTime = strtotime("2012-04-23T16:08:14.9-05:00");
$rowTime = strtotime("2012-04-23T16:08:16.1-05:00");
$timePassed = $rowTime - $pageTime;
echo $timePassed . "<br/><br/>";
Run Code Online (Sandbox Code Playgroud)
我希望看到的是"1.2",但strtotime()
忽略了字符串的毫秒部分.此外,显然microtime()
不会让你给它一个日期字符串...是否有一个替代函数来计算这个,或者我将不得不做一些字符串解析来提取秒和毫秒并减去?
Dan*_*Lee 13
请尝试使用DateTime.
这需要一些解决方法因为DateInterval
(返回的DateTime::diff()
)不计算微秒,所以你需要手动
$pageTime = new DateTime("2012-04-23T16:08:14.1 - 5 hours");
$rowTime = new DateTime("2012-04-23T16:08:16.9 - 5 hours");
// the difference through one million to get micro seconds
$uDiff = abs($pageTime->format('u')-$rowTime->format('u')) / (1000 * 1000);
$diff = $pageTime->diff($rowTime);
echo $diff->format('%s')-$uDiff;
Run Code Online (Sandbox Code Playgroud)
我总是建议DateTime
因为它的灵活性,你应该调查一下
编辑
为了向后兼容PHP 5.2,它采用与毫秒相同的方法:
$pageTime = new DateTime("2012-04-23T16:08:14.1 - 5 hours");
$rowTime = new DateTime("2012-04-23T16:08:16.9 - 5 hours");
// the difference through one million to get micro seconds
$uDiff = abs($pageTime->format('u')-$rowTime->format('u')) / (1000 * 1000);
$pageTimeSeconds = $pageTime->format('s');
$rowTimeSeconds = $rowTime->format('s');
if ($pageTimeSeconds + $rowTimeSeconds > 60) {
$sDiff = ($rowTimeSeconds + $pageTimeSeconds)-60;
} else {
$sDiff = $pageTimeSeconds - $rowTimeSeconds;
}
if ($sDiff < 0) {
echo abs($sDiff) + $uDiff;
} else {
// for the edge(?) case if $dt2 was smaller than $dt
echo abs($sDiff - $uDiff);
}
Run Code Online (Sandbox Code Playgroud)