PHP DateInterval创建间隔(微秒或毫秒)的时间间隔

问题描述 投票:1回答:1

如何在php中创建第二个DateInterval?例如:

0.123456秒

DateInterval::__construct的时间间隔规格

[不具有Ff与支持分秒的DateInterval::format类似。

Relative format listing的[DateInterval::createFromDateString也没有提到几分之一秒。

但是DateInterval class properties清单显示:

f微秒数,以秒为单位。

通过使用两个带有间隔秒的DateTimes的DateTime::diff,我可以瞬间获得DateInterval

示例:

$formatStr = 'Y-m-d H:i:s.u';
$dateTimeStr = '2000-01-01 00:00:00.0';
$timeZone = new \DateTimeZone('UTC'); 
$timerDateTimeStart = \DateTimeImmutable::createFromFormat($formatStr, $dateTimeStr, $timeZone);

$formatStr = 'Y-m-d H:i:s.u';
$dateTimeStr = '2000-01-01 00:00:00.123456';
$timeZone = new \DateTimeZone('UTC');
$timerDateTimeEnd = \DateTimeImmutable::createFromFormat($formatStr, $dateTimeStr, $timeZone);

$timerDiff = $timerDateTimeStart->diff($timerDateTimeEnd);
$intervalStr = $timerDiff->format('%Y-%M-%D %H:%I:%S.%f');
echo 'Interval (yyyy-mm-dd hh:mm:ss.sfract): ' . $intervalStr;

给予:

Interval (yyyy-mm-dd hh:mm:ss.sfract): 00-00-00 00:00:00.123456

因为DateTime支持其构造函数中的瞬间time_format,并且DateTime::createFromFormat理解

u微秒(最多6位数字),例如45、654321

BTW:您是否认为u(如果与DateTimeF一起使用,或者fDateInterval的情况下使用)有可能使您的一天变得更无聊?

我的解决方法之一可能是创建两个具有瞬间精度的DateTime,然后创建diff以具有相同的瞬间精度来创建DateInterval,但我想仅使用DateInterval来获得相同的结果。

您知道如何仅使用DateInterval来创建具有0.123456 secDateInterval吗?

php datetime precision intervals dateinterval
1个回答
0
投票

有一种方法可以使用DateInterval::createFromDateString

DateInterval::createFromDateString

输出:

$di = DateInterval::createFromDateString('123456 microseconds');
var_dump($di);

object(DateInterval)#1 (16) { ["y"]=> int(0) ["m"]=> int(0) ["d"]=> int(0) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["f"]=> float(0.123456) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(0) ["days"]=> bool(false) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) }

© www.soinside.com 2019 - 2024. All rights reserved.