如何使用 Date-FNS 将日期传递给函数?

How to pass a date to a function with Date-FNS?

我正在使用 Date-FNS 库来获取 difference between two dates in minutes。为什么 minutesDifference return NaN 如果日期像这样传递: getDateTime(2018, 3, 4, 15, 30, 0)

getDateTime: function (customDate) { 
var minutesDifference = differenceInMinutes(new Date(customDate), new Date()) 
console.log('minutesDifference: ' + minutesDifference) 
}

但这有效(没有 customDate 的硬编码版本):

getDateTime: function () { 
var minutesDifference = differenceInMinutes(new Date(2018, 3, 4, 15, 30, 0), new Date())
console.log('minutesDifference: ' + minutesDifference) 
}

我需要找到一种将自定义日期传递给函数的方法。

根据 date-fns documentationdifferenceInMinutes 期望传递一个 Date 对象。在您的 getDateTime 函数中:

getDateTime: function (customDate) { 
  var minutesDifference = differenceInMinutes(new Date(customDate), new Date()) 
  console.log('minutesDifference: ' + minutesDifference) 
}

您正在传递 new Date(customDate),并且在调用中您正在传递 getDateTime(2018, 3, 4, 15, 30, 0),因此分配给 customDate 的值是 2018,你实际上是在调用:

differenceInMinutes(new Date(2018), new Date());

其中 new Date(2018) 创建一个日期,该日期为 1970-01-01 开始后 2,018 毫秒。

I need to find a way to pass a custom date to the function.

确保 customDate 是一个 Date 对象,所以你不能使用

getDateTime(2018, 3, 4, 15, 30, 0);

您需要使用:

getDateTime(new Date(2018, 3, 4, 15, 30, 0)); // 2018-04-04 15:30:00

您还需要在调用 dateFns 函数前加上 dateFns.,例如

// https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js

function getDateTime(customDate) {
  var minutesDifference = dateFns.differenceInMinutes(new Date(customDate), new Date());
  console.log('minutesDifference: ' + minutesDifference) 
}

 getDateTime(new Date(2018, 3, 4, 15, 30, 0)); // 2018-04-04 15:30:00
 // Comparison in plain JS
 console.log(`Plain js: ${(new Date(2018, 3, 4, 15, 30, 0) - Date.now())/6e4 | 0}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
<script>dateFns.isToday(new Date())</script>