【问题标题】:Convert string returned by new Date().toString() back to a date using date-fns使用 date-fns 将 new Date().toString() 返回的字符串转换回日期
【发布时间】:2021-03-28 15:04:55
【问题描述】:

假设我制作了一个这样的日期: const myDate = new Date().toString()

使用 JS date-fns,我现在想将其转换回 Date 对象,以便我可以在其他 date-fns 中使用它(例如 differenceInSeconds)。

我该怎么做?

【问题讨论】:

  • 为什么不在转换为字符串之前简单地将新日期分配给一个变量哈哈

标签: javascript date-fns


【解决方案1】:

这样可以不用原生JS吗?

Date.parse(myDate);

【讨论】:

    【解决方案2】:

    您可以使用 Date.parse() 将其转换为自 UNIX 纪元以来的毫秒数,或使用 new Date() 将其转换为 Date 对象。 date-fns 接受这两个参数:

    const differenceInSeconds = require('date-fns/differenceInSeconds');
    const date1 = 'Thu Dec 17 2020 22:04:28 GMT+0000 (Greenwich Mean Time)';
    const date2 = 'Thu Dec 17 2020 22:13:34 GMT+0000 (Greenwich Mean Time)';
    
    differenceInSeconds(new Date(date2), new Date(date1));
    // => 546
    
    // OR
    differenceInSeconds(new Date(date2), Date.parse(date1));
    // => 546
    
    // OR
    differenceInSeconds(Date.parse(date2), Date.parse(date1));
    // => 546
    

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2021-10-06
      • 1970-01-01
      • 2019-09-03
      相关资源
      最近更新 更多