javascript - 无法使用 Javascript 将输入日期与当前日期进行比较

标签 javascript date

我在使用 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/

相关文章:

JavaScript 完全内联工作

javascript - 饼图( Highcharts )内的标签没有距离技巧

javascript - jQuery 是否限制大于语句的值?

javascript - 可枚举是什么意思?

php - MySQL 查询 : Retrieve 'birthdays' (YYYY-MM-DD) from the database, 并选择那些在当前周(无论年份)下降的那些。/PHP

javascript - 如何根据当前视口(viewport)大小选择将不同的 Prop 传递给 react 组件?

php - 确定另一个日期范围内的日期范围是否已满

r - 用于绘制时间序列数据的 x 轴刻度的日期格式

php - SQL 在 WHILE 循环中按日期排序

Java:解析并应用新模式后日期发生变化