且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

php从日期字符串获取microtime

更新时间:2023-11-06 18:16:46

请改用 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);
}