简体   繁体   English

无法使用jQuery UI的datepicker比较日期

[英]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: 我正在使用jQuery UI的Datepicker来解析日期并将其分配给变量:

//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. 现在我想将$ dtDate与$ 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() . 假设类“pmt-date”的字段是datepicker控制的<input>元素,则需要使用.val()而不是.text()来获取其值。

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

Your next line of code refers to a variable called "$date", not "$strDate", so: 您的下一行代码引用了一个名为“$ date”的变量,而不是“$ strDate”,因此:

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

Once you've got that, you can just directly compare the Date objects: 一旦你有了,你可以直接比较Date对象:

if ($dtDate < new Date())

There's no need to turn a newly-constructed Date object into a string and then back into a date. 无需将新构造的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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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