【问题标题】:What format timestamp is this in PHP and why can't i convert it using javascript?PHP 中的时间戳是什么格式的,为什么我不能使用 javascript 转换它?
【发布时间】:2020-08-16 13:00:51
【问题描述】:

我使用的这个 API 返回以下格式的时间戳。在他们的文档中仅将其解释为“UTC 时间戳”。我不知道这是什么格式,或者如何使用 javascript 转换它。我尝试过使用 new Date()、moment.js 以及介于两者之间的所有内容。谁能解释如何在 JS 而不是 PHP 中做到这一点?

// timestamp from api
20200430094700

使用 Javascript,我总能得到以下结果:

Friday, February 16, 2610 6:34:54.700 AM

这里我将使用 PHP 将其转换为正确的 unix 时间戳和日期对象

$timestamp = 20200430094700;

$e = new DateTime($timestamp);

// This is the correct Unix timestamp
// 1588258020
echo date_timestamp_get($e);        

// This is the correct date
// [date] => 2020-04-30 09:47:00.000000
print_r($e);

【问题讨论】:

标签: javascript php timestamp unix-timestamp


【解决方案1】:

正如 cmets 中所指出的,20200430094700 不是时间戳,而是YYYYMMDDHHMMSS 格式的日期。要将其转换为 JavaScript 中的 Date,您需要提取组件部分(使用例如 .slice),从月份中减去一个以使其成为 JS 月份(从 0 开始索引),然后将其传递给 Date.UTC并在Date 构造函数中使用它的输出:

const ts = '20200430094700';

const d = new Date(Date.UTC(ts.slice(0,4), ts.slice(4,6)-1, ts.slice(6,8), ts.slice(8,10), ts.slice(10,12), ts.slice(12,14)));
console.log(d);

【讨论】:

    猜你喜欢
    • 2014-01-16
    • 1970-01-01
    • 2021-09-20
    • 2013-12-25
    • 2013-05-11
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2015-09-08
    相关资源
    最近更新 更多