简体   繁体   中英

Can't Compare dates using jQuery UI's datepicker

Ok, so I am attempting to test if a date is older than today. I am using jQuery UI's Datepicker to parse the date and assign it to a variable:

//Get Date as String
var $strDate = $(".pmt-date").text();
//Parse Date
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);

Then I get today's date and assign it to a variable:

//Get Today's Date
var $strToday $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);

Now I would like to compare $dtDate with $tDate. This is what I have tried:

if($dtDate > $tDate)
{
     alert("Payment Date is Greater");
}
else
{
     alert("Today's Date is Greater");
}

When I test this, I ALWAYS get the alert "Today's Date is Greater". I can display my two date variables via an alert, and I see the dates in correct format. So why does this comparison fail to work when the parse is working correctly?

Assuming that the field with class "pmt-date" is the datepicker-controlled <input> element, you need to fetch its value with .val() , not .text() .

var $strDate = $(".pmt-date").val();

Your next line of code refers to a variable called "$date", not "$strDate", so:

var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);

Once you've got that, you can just directly compare the Date objects:

if ($dtDate < new Date())

There's no need to turn a newly-constructed Date object into a string and then back into a date. I guess you're Date to string and back in order to strip off the time-of-day part of the date, so that's not really a bad way to do it.

In date comparisons, more than means the date comes after, and less than means the date comes before. Older than would imply that the date comes before, and thus you want to use less than

if($dtDate < $tDate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM