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

3

我正在尝试在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 中复制该功能?


dateParser() 被如何调用并传递了什么参数? - Brett DeWoody
你能执行 console.log(typeof input) 吗? - TGrif
@TGrif 对象被返回 - David Jarvis
1
由于您将日期对象而不是字符串传递给dateParser函数,因此会出现“_input.substring不是函数_”错误。您可以使用Date.parse()来获取日期的Unix时间戳表示。 - TGrif
4个回答

21

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

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


3
如果有人需要将当前时间转换为Unix时间戳,应该使用 Math.floor 函数,否则会生成一个稍微超前一点的时间。实际上,我认为始终使用 Math.floor 更为恰当,因为通常希望舍弃精度。 - Richard Scarrott

3

我建议使用 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处理日期/时间非常有效。


0
Unix时间戳是从特定日期开始的秒数。Javascript函数getTime()返回从同一特定日期到您指定日期的毫秒数。
因此,如果您将函数结果除以数字1000,则会得到Unix时间戳并从毫秒转换为秒。不要忘记忽略小数位。
您收到的错误消息是因为输入值不是字符串。

0

如果系统时区未设置为UTC,则有两个选项会产生略微不同的结果

选项1-忽略系统时区

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

> 1577836800

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

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

> 1577854800

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接