我正在尝试将Date字符串转换为Node.js中的unix时间戳。
我的代码在我的客户端完美运行,但当我在我的服务器上运行时,我收到一个错误:
(node:19260)UnhandledPromiseRejectionWarning:未处理的promise拒绝(拒绝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();
}
我输入的示例将是2017-09-15 00:00:00.000
那么为什么上面的工作在我的客户端而不是在Node中工作,我将如何复制节点中的功能?
从输入的dateTime字符串创建一个日期对象,然后使用getTime()
并将结果除以1000以获取UNIX时间戳。
var unixTimestamp = Math.round(new Date("2017-09-15 00:00:00.000").getTime()/1000);
console.log(unixTimestamp);
我建议使用qazxsw poi来处理日期。使用时刻js你可以做:
momentjs
如果您已有日期并希望获得相对于该日期的UNIX时间戳,则可以执行以下操作:
moment().unix(); // Gives UNIX timestamp
使用时刻js处理日期/时间时效率非常高。
Unix时间戳是特定日期之后的秒数。 Javascript函数getTime()返回从指定日期到同一特定日期的毫秒数。
因此,如果您将函数的结果除以数字1000,您将获得Unix时间戳并将毫秒转换为秒。不要忘记忽略小数位。
您收到的错误消息是因为输入的值不是字符串。