繁体   English   中英

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

[英]How to pass a date to a function with Date-FNS?

我正在使用Date-FNS库以分钟为单位获取两个日期之间差额 如果日期这样传递,为什么minutesDifference返回NaNgetDateTime(2018, 3, 4, 15, 30, 0) 2018,3,4,15,15,30,0 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) 
}

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

按照日期FNS文档 ,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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM