我在使用 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");
}
在这里,我收到了其他部分
警报消息,其中用户输入日期晚于今天的日期。
最佳答案
问题在于 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
关于javascript - 无法使用 Javascript 将输入日期与当前日期进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55428826/