使用 date-fns 将 new Date().toString() 返回的字符串转换回日期

Convert string returned by new Date().toString() back to a date using date-fns

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

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

我该怎么做?

能不能这样用原生JS?

Date.parse(myDate);

您可以使用 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