Node.js将日期字符串转换为unix时间戳
问题描述:
我试图在Node.js中将日期字符串转换为unix时间戳。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中,以及如何复制n中的功能颂?
答
从您输入的日期时间字符串中创建一个日期对象,然后使用getTime()
并将结果除以1000以获得UNIX时间戳。
var unixTimestamp = Math.round(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时间戳并从毫秒转换为秒。不要忘记忽略小数位。
您收到的错误消息是因为输入的值不是字符串。
如何调用'dateParser()'以及传递给它的是什么? –
你可以'console.log(typeof输入)'? – TGrif
@TGrif对象返回 –