gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:30:19 24 4
gpt4 key购买 nike

如何在 PHP 中创建瞬间 DateInterval?例如:

0.123456 sec

DateInterval::__construct 的间隔规范

没有F,也没有f,类似于支持分秒的DateInterval::format

Relative format listing 中的 DateInterval::createFromDateString 也没有提及秒的任何分数。

但是 DateInterval class properties 列表显示:

f Number of microseconds, as a fraction of a second.

我能够通过使用两个具有秒数的 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 Microseconds (up to six digits) Example: 45, 654321

顺便说一句:您不认为 u 在使用 DateTimeFf 的情况下> 如果 DateInterval 有可能让你的一天变得不那么无聊?

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

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

基于已接受答案的解决方案:

$dateInterval = DateInterval::createFromDateString("1 day, 2 hours, 3 minutes, 1 second, 123456 microsecond");
$intervalStr = $dateInterval->format('%D %H:%I:%S.%F');
echo 'Interval (dd hh:mm:ss.sfract): ' . $intervalStr . PHP_EOL;

给出:

Interval (dd hh:mm:ss.sfract): 01 02:03:01.123456

最佳答案

有一种方法可以使用 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)
}

Demo on 3v4l.org

来自手册:

time

A date with relative parts. Specifically, the relative formats supported by the parser used for strtotime() and DateTime will be used to construct the DateInterval.

关于PHP DateInterval 创建瞬间(微秒或毫秒)间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60022084/

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