Node.js将datestring转换为unix时间戳

我试图在Node.js中将datestring转换为unix时间戳。

我的代码在我的客户端完美工作,但是当我在我的服务器上运行它我得到一个错误:

(node:19260)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):TypeError:input.substring不是函数

我的代码:

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(); } 

我的input示例为2017-09-15 00:00:00.000

那么,为什么上述工作在我的客户端,但不是在节点,以及如何复制节点中的function?

从input的dateTimestring中创build一个date对象,然后使用getTime()并将结果除以1000以获得UNIX时间戳。

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

我会推荐使用momentjs来处理date。 使用momentjs你可以做到:

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

如果你已经有一个date,并且想获得相对于该date的UNIX时间戳,你可以这样做:

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

当使用momentjs处理date/时间时,它会非常高效。

Unix时间戳是从特定date开始的秒数。 Javascript函数getTime()返回指定date之前的相同特定date的毫秒数。

所以,如果你把你的函数的结果除以数字1000,你将得到Unix时间戳,并从毫秒转换为秒。 不要忘记忽略小数位。

您收到的错误消息是因为input的值不是string。