- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在 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
在使用 DateTime
和 F
或 f
的情况下> 如果 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)
}
来自手册:
time
A date with relative parts. Specifically, the relative formats supported by the parser used for
strtotime()
andDateTime
will be used to construct the DateInterval.
关于PHP DateInterval 创建瞬间(微秒或毫秒)间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60022084/
我目前正在考虑从 JodaTime 迁移到 java8 api。 大多数都可以,但有一件事让我望而却步。我需要计算一个人的工作类次有多少是在“办公时间”内。 使用 JodaTime,我利用 Insta
在注册期间,我的 iOS 应用程序中有一个 View Controller ,用户可以选择跳过。但是,如果他们开始该步骤,则他们要么必须完成它,要么点击撤消,这样就不会保存部分信息。为了确保这一点,我
我创建了一个 playground 并将我的 Swift 文件添加到它的 source 文件夹中,这样我就可以访问类并根据需要实例化它们,但我需要更多地使用 playground! 我在 Sprite
我是一名优秀的程序员,十分优秀!