[英]moment.js not factoring in the year when converting a date to Unix timestamp
我需要找到2个日期30/05/2019和30/04/2020之间的差额。 我正在使用此代码:
var checkinTime = moment('30/05/2019', 'DD/MM/YYYY').unix();
var checkoutTime = moment('30/04/2020', 'DD/MM/YYYY').unix();
2019年的值是正确的,但返回的2020年值好像是2019年。返回的值分别是'1590760800'和'1588168800'。 第一个时间戳应该小于第二个时间戳,但是要大一些(一个月)。
如何考虑未来的几年?
您的代码似乎是正确的。 我尝试了以下代码。
index.js
var moment = require('moment');
var checkinTime = moment('30/05/2019', 'DD/MM/YYYY').unix();
var checkoutTime = moment('30/04/2020', 'DD/MM/YYYY').unix();
console.log(' checkinTime: ' + checkinTime);
console.log('checkoutTime: ' + checkoutTime);
console.log(' diff dates: ' + (checkoutTime - checkinTime) / 86400);
checkinTime小于checkoutTime,日期差为336,如下所示。
$ node index.js
checkinTime: 1559142000
checkoutTime: 1588172400
diff dates: 336
这是纯JavaScript的示例。
请注意,Javascript中的日期对象具有时间戳,分辨率为毫秒,而Unix时间通常以秒为单位。
function parseDDMMYYY(input) { const dateArrayText = input.match(/^(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})$/); if (!dateArrayText) return NaN; // Decode dateArrayText to numeric values that can be used by the Date constructor. const date = { year : +dateArrayText[3], month : (+dateArrayText[2]) - 1, // month is zero based in date object. day : +dateArrayText[1] } const dateObject = new Date( date.year, date.month, date.day ); // Check validity of date. The date object will accept 2000-99-99 as input and // adjust the date to 2008-07-08. To prevent that, and make sure the entered // date is a valid date, I check if the entered date is the same as the parsed date. if ( !dateObject || date.year !== dateObject.getFullYear() || date.month !== dateObject.getMonth() || date.day != dateObject.getDate() ) { return NaN; } return dateObject; } const date1 = parseDDMMYYY('30/05/2019'); const date2 = parseDDMMYYY('30/04/2019'); const diffInMs = date2 - date1; const diffInSeconds = Math.floor( (date2 - date1) / 1000 ); console.log( diffInMs ); console.log( diffInSeconds );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.