【问题标题】:Node.js converting date string to unix timestampNode.js 将日期字符串转换为 unix 时间戳
【发布时间】:2017-09-15 10:43:41
【问题描述】:

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

下面的代码在我的客户端上完美运行,但是当我在服务器上运行它时出现错误:

(node:19260) UnhandledPromiseRejectionWarning: UnhandledPromiseRejectionWarning: 未处理的承诺拒绝 (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() 是如何被调用的以及传递给它的是什么?
  • 你能console.log(typeof input) 吗?
  • @TGrif 对象返回
  • 由于您没有将字符串而是日期对象传递给 dateParser 函数,因此您会收到 input.substring is not a function 错误。您可以使用 Date.parse() 来获取日期的 Unix 时间戳表示。

标签: javascript node.js unix-timestamp


【解决方案1】:

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

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

【讨论】:

  • 对于任何将当前时间转换为 unix 时间戳的人,您应该使用Math.floor,否则您将在未来生成一个非常小的时间。事实上,我认为Math.floor 总是更合适,因为通常需要放弃精度。
【解决方案2】:

我会推荐使用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 处理日期/时间时,它会变得非常高效。

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

      如果系统时区未设置为 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
      

      【讨论】:

        猜你喜欢
        • 2011-03-16
        • 1970-01-01
        • 2019-07-30
        • 2012-06-23
        • 2011-09-23
        • 2022-01-21
        • 2012-09-01
        • 1970-01-01
        相关资源
        最近更新 更多