php从日期字符串获取microtime [英] php get microtime from date string

查看:123
本文介绍了php从日期字符串获取microtime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取两个日期时间字符串(包括毫秒)之间的时间

I am trying to get the time passed between two datetime strings (including milliseconds)

示例:

$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()不允许您给它一个日期字符串...是否有替代函数可以计算出来,还是我必须做一些字符串解析以提取秒和毫秒并减去?

What I want to see echoed is "1.2" but strtotime() ignores the millisecond part of the string. Also, apparently microtime() doesn't let you give it a datestring... Is there an alternative function for calculating this, or am I going to have to do some string parsing to extract the seconds and milliseconds and subtract?

推荐答案

请改用 DateTime .

这需要一些解决方法,因为DateInterval(由DateTime::diff()返回)不会计算微秒,因此您需要手动进行计算

This needs a bit of a workaround because DateInterval (which is returned by DateTime::diff()) doesn't calculate the microseconds, so you need to this by hand

$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,您应该仔细研究

I always recommend DateTime because of its flexibility, you should look into it

编辑

为了向后兼容PHP 5.2,它采用与毫秒相同的方法:

For backwards compability to PHP 5.2 it takes the same approach as for the milliseconds:

$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);
}

这篇关于php从日期字符串获取microtime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆