【问题标题】:Could not compare input date with current date using Javascript无法使用 Javascript 将输入日期与当前日期进行比较
【发布时间】:2019-08-21 01:37:00
【问题描述】:

我在使用 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 警报消息,其中用户输入的日期晚于今天的日期。

【问题讨论】:

标签: javascript date


【解决方案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

【讨论】:

【解决方案2】:

顺便说一句,以后试试momentJS。它是许多开发人员用来处理时间和日期的第三方库,因为我们都知道这在原生 Javascript 中很痛苦。

https://momentjs.com

【讨论】:

    【解决方案3】:

    不要使用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");
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多