在 PHP 中将时间戳转换为点 ("yyyy.mm.dd hh:nn:ss.zzz")

我正在尝试使用匈牙利日期时间格式转换字符串,但由于点分隔符而没有成功:


<?php

$dtime = DateTime::createFromFormat("YY'.'MM'.'DD HH:MM:II frac", "2020.07.22 22:41:36.258");

$timestamp = $dtime->getTimestamp();

echo("Result: " . $timestamp . "<br>");

?>

没有像这样的“字符串替换”是不可能的吗:

strtotime(preg_replace("/([0-9]{4})\.([0-9]{2})\.([0-9]{2})/",'${1}-${2}-${3}',$xml->delivery_time))?


(我是 PHP 5 的新手,我很震惊它不能简单地转换通用日期格式。搜索了 200 多个结果,浪费了 4 个多小时......没有成功。)


哈士奇WWW
浏览 98回答 2
2回答

蝴蝶不菲

正确的格式存储在$format变量中:(注意:v(millisec) 修饰符是从 v7.3 开始才添加的)<?php$format = 'Y.m.d H:i:s.v';$dtime = DateTime::createFromFormat($format, "2020.07.22 22:41:36.258");$timestamp = $dtime->getTimestamp();echo("Result: " . $timestamp . "<br>");?>Result: 1595457696

慕的地10843

该解决方案也适用于 7.3 以下的 PHP 版本// convert a hungarian datetime to a timestampfunction toTimestamp($dt){&nbsp; &nbsp; $format = 'Y.m.d H:i:s.';&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (version_compare(PHP_VERSION, '7.3.0', '<')) {&nbsp; &nbsp; &nbsp; &nbsp; $dt = explode('.', $dt);&nbsp; &nbsp; &nbsp; &nbsp; $dt[3] = intval($dt[3] * 1000);&nbsp; &nbsp; &nbsp; &nbsp; $dt = implode('.', $dt);&nbsp; &nbsp; &nbsp; &nbsp; $format .= 'u';&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; $format .= 'v';&nbsp; &nbsp; }&nbsp; &nbsp; return DateTime::createFromFormat($format, $dt)->getTimestamp();}$timestamp = toTimestamp('2020.07.22 22:41:36.258');var_dump($timestamp);
打开App,查看更多内容
随时随地看视频慕课网APP