PHP 中的日期时间到时间戳(以毫秒为单位)

Datetime to Timestamp in milliseconds in PHP

我想根据输入“2016-03-22 14:30”创建一个以毫秒为单位的时间戳。 此外,指定的时区应为 Australia/Sydney.

我尝试了不同的方法,但 none 似乎有效。

有人可以帮帮我吗?我真的很纠结。

很好的自我解释代码,所以我不会说太多。

date_default_timezone_set('Australia/Sydney'); // set timezone
$yourdate = '2016-03-22 14:30';
$stamp = strtotime($yourdate); // get unix timestamp
$time_in_ms = $stamp*1000;

如果你想正常显示。

echo number_format($time_in_ms, 0, '.', '');

尝试一下它会起作用

<?php
$date = new DateTime('@'.strtotime('2016-03-22 14:30'), new DateTimeZone('Australia/Sydney'));

echo "Timestamp in Australia/Sydney: ".$date->format('Y-m-d H:i:sP');
echo "<br/>";
echo "Timestamp in miliseconds Australia/Sydney: ".strtotime($date->format('Y-m-d H:i:sP'));
?>

输出:

Timestamp in Australia/Sydney: 2016-03-22 18:30:00+00:00
Timestamp in miliseconds Australia/Sydney: 1458671400
date_default_timezone_set("Australia/Sydney");
echo strtotime('2016-03-22 14:30') * 1000;

输出:1458617400000

您可以使用 DateTimecreateFromFormat 方法,或者更好的方法是 DateTimeImmutable,同时将时区作为第三个参数传递。这样你就不需要依赖默认时区,这绝不是一个好主意

$datetime = DateTimeImmutable::createFromFormat('Y-m-d H:i', '2016-03-22 14:30', new DateTimeZone('Australia/Sydney'));
echo $datetime->getTimestamp();
echo $datetime->format(DateTime::ISO8601);

您也可以将其转换为另一个时区,请注意它生成了新的 DateTimeImmutable 并且原始版本保持不变:

echo $utcTzDatetime = $date->setTimezone(new DateTimeZone('UTC'));
echo $utcTzDatetime->format(DateTime::ISO8601);
echo $datetime->format(DateTime::ISO8601);

更新:

如果格式不固定,可以让DateTime自己猜:

new DateTimeImmutable($time, new DateTimeZone('Australia/Sydney'));

但请注意,如果 $time 字符串包含时区或偏移量,例如 '2016-03-22T14:30-0500',它将优先于时区参数并导致不同的时间戳!

如果您使用的是 Carbon 包,那么您可以使用

Carbon::parse('2009-09-22 16:47:08.128')->micro

这将 return 您以微秒为单位计算时间。您可以将其除以 1000 并将其与相同日期的纪元时间戳(以秒为单位)连接起来。
只要确保如果日期格式没有毫秒分量,那么您将得到 0 作为微秒,并且您必须在连接之前用额外的零填充该 0。

简单试试这个方法

<?php
$time = microtime(true);
$datetime = new DateTime();
$datetime->setTimestamp($time);
$format = $datetime->format('Y-m-d H:i:s');
var_dump($format);
?>

对于那些寻找如何从 DateTime 获取以毫秒为单位的时间戳的人,这就是我想出的:

$date = new DateTimeImmutable();

$timestampMs = (int) ($date->getTimestamp() . $date->format('v'));

这会获取以秒为单位的时间戳并附加毫秒 ('v' format)。

https://3v4l.org/UoZsL

带有 * 1000 的答案仅格式化输出,但不捕获精度。

使用 DateTime->format,其中 U 代表秒,u 代表微秒,v 代表毫秒:

<?php
// pass down `now` or a saved timestamp like `2021-06-15 01:03:35.678652`
$now = new \DateTime('now', new \DateTimeZone('UTC'));
// or something like:
$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''), new \DateTimeZone('UTC'));

// in microseconds:
$now_us = (int)$now->format('Uu');
// e.g.: 1623719015678652


// in milliseconds:
$now_ms = (int)$now->format('Uv');
// e.g.: 1623719015678