比较2个日期一个是jquery对象,另一个是文本框

Comparing 2 Dates One is jquery Object and other is in textbox

本文关键字:对象 jquery 另一个 文本 一个 日期 2个 比较      更新时间:2023-09-26

我正在尝试比较两个日期,一个是在文本框中写为YYYY-MM-DD,另一个是jquery Datepicker实例

我用自定义包装器函数调用函数

datePicker('#edd', {onSelect: function(str, obj){ check_if_edd_less_OD(str, obj); }});

和下面是比较日期的JS函数

function check_if_edd_less_OD(s, o) {
    console.clear();
    var eddDate = new Date();
    eddDate.setDate(o.selectedDay);
    eddDate.setMonth(o.selectedMonth);
    eddDate.setYear(o.selectedYear);
    orderDate = $('#orderdate').val().split('-');
    console.log(orderDate);

    var odDate = new Date();
    odDate.setDate(parseInt(orderDate[2], 10));
    odDate.setMonth(parseInt(orderDate[1], 10));
    odDate.setYear(parseInt(orderDate[0], 10));

    console.log(eddDate);
    console.log(odDate);

    if (odDate.getTime() < eddDate.getTime()) {
        console.log('You shall Pass');
    } else {
        console.log('You shall NOT Pass');
    }

}

截至今天,订单日期输入设置为2013-03-07,如果我从日期选择器中选择5 APR 2013,它不起作用

下面是console

的输出
["2013", "03", "07"]
Date {Fri Apr 05 2013 16:55:23 GMT+0500 (Pakistan Standard Time)}
Date {Sun Apr 07 2013 16:55:23 GMT+0500 (Pakistan Standard Time)}
You shall NOT Pass

你可以看到console.log(eddDate);给出正确的输出,但console.log(odDate);给出的是2013年4月7日。

问题:为什么会有这样的行为?

Date对象的月份计数从零开始(January:0,…,April:3)。不确定o.selectedMonth是什么格式,但解析后的YYY-MM-DD日期应该更改为

odDate.setMonth(parseInt(orderDate[1], 10)-1);

顺便说一句,在比较两个Date对象之前,您不需要调用getTime(),它们将自动转换为该数字。