繁体   English   中英

Node.js 将日期字符串转换为 unix 时间戳

[英]Node.js converting date string to unix timestamp

我正在尝试将日期字符串转换为 Node.js 中的 unix 时间戳。

我下面的代码在我的客户端上运行良好,但是当我在我的服务器上运行它时,我收到一个错误:

(node:19260) UnhandledPromiseRejectionWarning: Unhandled promise Rejection (rejection id: 1): TypeError: input.substring is not a function

我的代码:

function dateParser(input) {
    // function is passed a date and parses it to create a unix timestamp

    // removing the '.000' from input
    let finalDate = input.substring(0, input.length - 4);
    return new Date(finalDate.split(' ').join('T')).getTime();
}

我的输入示例是2017-09-15 00:00:00.000

那么为什么上述内容在我的客户端上有效,但在 Node 中无效,我将如何在 Node 中复制该功能?

从输入的 DateTime 字符串创建一个日期对象,然后使用getTime()并将结果除以 1000 以获得 UNIX 时间戳。

 var unixTimestamp = Math.floor(new Date("2017-09-15 00:00:00.000").getTime()/1000); console.log(unixTimestamp);

我会推荐使用momentjs来处理日期。 使用momentjs你可以这样做:

moment().unix(); // Gives UNIX timestamp

如果您已经有一个日期并希望获得相对于该日期的 UNIX 时间戳,您可以执行以下操作:

moment("2017-09-15 00:00:00.000").unix(); // I have passed the date that will be your input 
// Gives out 1505413800

使用 momentjs 处理日期/时间时会变得非常高效。

Unix 时间戳是距特定日期的秒数。 Javascript 函数 getTime() 返回从同一特定日期到您指定的日期之间的毫秒数。

因此,如果您将函数的结果除以数字 1000,您将获得 Unix 时间戳并将毫秒转换为秒。 不要忘记忽略小数位。

您收到的错误消息是因为 input 的值不是字符串。

如果系统时区未设置为 UTC,则 2 个选项的结果略有不同

选项 1 - 忽略系统时区

console.log(Math.floor(new Date("2020-01-01").getTime()/1000));

> 1577836800

选项 2 ("moment.js") - 时间戳会因系统时区而异

console.log(moment('2020-01-01').unix());

> 1577854800

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM