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

时间:2018-04-08 18:25:11

标签: javascript date date-fns

我正在使用Date-FNS库来获取difference between two dates in minutes。如果日期如下所示, minutesDifference 为什么会返回 NaN library(ggraph) ggraph(g) + geom_edge_link(aes(edge_colour = color, edge_width = abs(statistic))) + geom_node_text(aes(label = name)) + scale_edge_color_manual(values = c('green' = 'green', 'red' = 'red'))

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

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

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

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

1 个答案:

答案 0 :(得分:1)

根据date-fns documentation differenceInMinutes 期望传递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毫秒。

  

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

确保 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>