gpt4 book ai didi

php 从日期字符串中获取时间

转载 作者:IT王子 更新时间:2023-10-29 00:18:10 25 4
gpt4 key购买 nike

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

例子:

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

最佳答案

试试 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;

我总是推荐 DateTime 因为它的灵 active ,你应该研究一下

编辑

为了向后兼容 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);
}

关于php 从日期字符串中获取时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10289160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com