php strtetime不适用于微秒

4xrmg8kj  于 2022-12-25  发布在  PHP
关注(0)|答案(3)|浏览(126)

strtotime函数在试图将一个包含微秒的字符串转换成unix时间戳时似乎无法工作,我不关心在unix时间戳中保留微秒。
示例:

$date = '2017-03-21-10:58:01.7888';
echo strtotime($date); // always outputs 0
bihw5rsg

bihw5rsg1#

根据these tests和PHP手册,问题在于日期和时间之间的破折号:
5.0.0开始允许微秒,但它们被忽略。

7z5jn7bk

7z5jn7bk2#

I had the same problem and came up with this solution:

function strtotimeMicro($str)
{
    $secs = (string) strtotime($str);
    $t = new DateTimeImmutable($str);
    $micro = $t->format("u");
    $ts = $secs.$micro;
    return (int) $ts;
}

$date = '2017-03-21 10:58:01.7888';
echo strtotimeMicro($date); // returns 1490090281788800
b4lqfgs4

b4lqfgs43#

PHP不支持带微秒的格式,请参见list of compound formats(date and time)。您必须将其转换为支持的格式。如果时间戳保证使用此格式,则可以在点处拆分,然后使用第一部分获得不带微秒的时间戳:

echo strtotime(split(".", $data)[0]);

相关问题