使用JavaScript比较两个日期时,我得到了错误的结果。我在下面解释我的代码。
var user_date='01-04-2019';
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = '0' + todayDay;
}
if (todayMonth < 10) {
todayMonth = '0' + todayMonth;
}
var todayDateText = todayDay + "-" + todayMonth + "-" + todayYear;
var inputToDate = Date.parse(user_date);
var todayToDate = Date.parse(todayDateText);
console.log(todayDateText);
//console.log(mydate);
if (inputToDate > todayToDate) {
alert("the input is later than today");
}else{
alert("the input is earlier than today");
}
在这里,我收到else part
警报消息,其中用户输入日期晚于今天。
答案 0 :(得分:1)
问题出在Date.parse()
上,无法正确解析DD-MM-YYYY
。这是一个MM-DD-YYYY
(注意: YYYY-MM-DD
recommended)
var user_date = '03-01-2019'; // MM-DD-YYYY
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = '0' + todayDay;
}
if (todayMonth < 10) {
todayMonth = '0' + todayMonth;
}
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(user_date);
var todayToDate = Date.parse(todayDateText);
console.log(inputToDate, todayToDate);
console.log(user_date, todayDateText);
if (inputToDate > todayToDate) {
alert("the input is later than today");
} else {
alert("the input is earlier than today");
}
要将DD-MM-YYYY
转换为MM-DD-YYYY
,请使用
var user_date ='01-03-2019'; // DD-MM-YYYY
var datePieces = user_date.split("-");
console.log([datePieces[1] , datePieces[0] , datePieces[2]].join("-")); // 03-01-2019
答案 1 :(得分:0)
顺便说一句,将来尝试 momentJS 。这是一个第三方库,许多开发人员都使用该库来处理时间和日期,因为我们都知道这是香草Javascript的痛苦。
答案 2 :(得分:0)
请勿使用Date.parse
。不能保证理解格式为dd-mm-yyyy
的日期字符串:
console.log(Date.parse('01-04-2019'))
相反,请使用2+-argument Date
constructor并直接比较日期:
var userDate = new Date(2019, 3 /* months are 0-indexed */, 1);
var todayDate = new Date();
// drop the time part of todayDate
todayDate.setHours(0, 0, 0, 0);
if (userDate > todayDate) {
alert("the input is later than today");
} else {
alert("the input is no later than today");
}