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

Hya*_*the 5 php timestamp milliseconds

我想从输入'2016-03-22 14:30'创建一个以毫秒为单位的时间戳.指定的时区也应该是澳大利亚/悉尼.

我尝试了不同的方法,但似乎都没有.

有人可以帮我吗?我真的很挣扎.

Mic*_* B. 23

答案* 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
Run Code Online (Sandbox Code Playgroud)


Kyl*_*lie 10

非常自我解释的代码,所以我不会说太多.

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;
Run Code Online (Sandbox Code Playgroud)

如果要正确显示它.

echo number_format($time_in_ms, 0, '.', '');
Run Code Online (Sandbox Code Playgroud)

  • @KyleK 可能他需要这种方式来连接到只接受毫秒时间戳的 API,因为这正是我得出这个答案的原因 (3认同)
  • 你错过了 - *以毫秒为单位*我猜。 (2认同)
  • 这不是以毫秒为单位,这是以秒*1000为单位 (2认同)