[英]Why moment.js producing Invalid Date for certain dates only?
我無法弄清楚到底是什么與該功能有關。 用戶可以從下拉菜單中選擇的天數。 這些天是: [3, 7, 14, 21, 28, 30, 60, 90, 180, 365]
因此,當用戶選擇3
,moment.js會將其轉換為適當的ISO日期。 但是,如果用戶選擇7、14或21,則會生成“無效日期”,但對其他所有內容都有效。 這是怎么回事?
vm.getSelectedDate = function (days) {
console.log(days);
if (vm.selectedReminderDay) {
vm.selectedReminderDate = new Date(vm.today);
console.log(vm.selectedReminderDate);
vm.selectedReminderDate.setDate(vm.today.getDate() + days);
console.log(vm.selectedReminderDate);
var m = moment(vm.selectedReminderDate, "MM/DD/YYYY h:mm:ss A");
console.log(m);
vm.utcReminderDate = m.toISOString();
console.log(vm.utcReminderDate);
return "in " + vm.selectedReminderDay + " days";
}
else {
return "When?"
}
}
Date.getDate()
獲取當月的當前日期,當它超出范圍時(通常超過30左右),將導致意外的行為。 您可以使用Date.getTime()
:
vm.selectedReminderDate.setTime(vm.today.getTime() + (days*24*60*60*1000));
乘法只是將setTime
期望的天數轉換為毫秒。
但是更好的方法是僅使用momentjs來操縱日期,如下所示:
vm.getSelectedDate = function (days) {
if (vm.selectedReminderDay) {
var newdate = moment(vm.today).add(days, 'days');
vm.utcReminderDate = newdate.toISOString();
return "in " + vm.selectedReminderDay + " days";
}
else return "When?";
}
更好地使用momentjs的建議在其他答案中也有效。
7、14和21似乎是唯一不正確的數字的實際原因是您試圖用於解析的格式。 Moment似乎將您的Date對象轉換為一個字符串進行解析,並且幾個月的“ MM”部分與轉換后的字符串中的day部分匹配。 因此,當月日期不在1到12范圍內的任何日期都無法正常工作。 如果在另一天運行相同的代碼,則會發現其他幻數。
我不太了解MM如何與日期部分匹配,在您所在的地區可能與我的日期有所不同,但我相信這是要點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.