我试图让两个时间日期时间字符串(包括毫秒)之间传递
例:
$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/>";
我想看到呼应为“1.2”,但strtotime()
忽略字符串的毫秒部分。 另外,显然microtime()
不会让你给它一个datestring ......有没有计算这个替代功能,还是我将不得不做一些字符串解析提取秒和毫秒核减?
与试用日期时间来代替。
这需要一些变通方法,因为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;
我总是建议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);
}
丹李的回答为基础,这里有一个普遍的工作方案:
$pageTime = new DateTime("2012-04-23T16:08:14.9-05:00");
$rowTime = new DateTime("2012-04-23T16:08:16.1-05:00");
$uDiff = ($rowTime->format('u') - $pageTime->format('u')) / (1000 * 1000);
$timePassed = $rowTime->getTimestamp() - $pageTime->getTimestamp() + $uDiff;
完整的解释:
- 我们存储在这两个日期之间的微秒签署差异
$uDiff
并通过1000 * 1000除以转换结果在几秒钟内 - 在操作数的顺序
$uDiff
是重要的,必须是一样的$ timePassed操作。 - 我们计算的Unix时间戳(全称秒)两个日期之间的差异,我们添加了微妙的差异,以获得想要的结果
- 使用
DateTime::getTimestamp()
会给出一个正确的答案,即使当差值大于60秒