Domanda

I have been trying to work with comparing dates and times using jQuery UI's datepicker and the timepicker add-on (an add-on I have just discovered and am very happy with).

So, here's what I have:

First, the expected values from the $("#dateOfAb").val() and the $("#dateOfAb2").val() both use the datetimepicker with the following formatting:

Time:

$("#dateOfAb, #dateOfAb2").datetimepicker({ timeFormat: "hh:mm tt", stepMinute: 15 });

AND, although not explicitly set (It seems to be the default date formatting for said plug-in):

dateFormat: "mm/dd/yy"

(example output: 08/16/2013 12:00 am)

So, I need to compare these dates and while I have had success comparing dates in the past, I am having trouble comparing times for equal dates (which is the ultimate goal), but what is holding me up right now is the fact that I can't get these two parseDate values (on substrings from the full date/time) to show that they are equal when the dates are the same.

Okay, that last paragraph may be a little confusing so, here's the code:

$("#dateOfAb2").change(function () {
    console.log("FIRST SET: " + $.datepicker.parseDate("mm/dd/yy", $("#dateOfAb").val().substring(0, 9)))
    console.log("FIRST SET: " + $.datepicker.parseDate("mm/dd/yy", $("#dateOfAb2").val().substring(0, 9)))

    if ($.datepicker.parseDate("mm/dd/yy", $("#dateOfAb").val().substring(0, 9)) == $.datepicker.parseDate("mm/dd/yy", $("#dateOfAb2").val().substring(0, 9))) {
        alert("The dates are tied.");
        console.log("SECOND SET: " + $.datepicker.parseDate("mm/dd/yy", $("#dateOfAb").val().substring(0, 9)))
        console.log("SECOND SET: " + $.datepicker.parseDate("mm/dd/yy", $("#dateOfAb2").val().substring(0, 9)))
    }
});

The problem is that even when I know the values are exactly the same (proven with console.log() [image below]) they don't seem to compare as I would expect in my if branch.

Image of console after running:

enter image description here

You can see that I have substringed out just the date part of the value and the values are the same, but I'm not sure what I'm doing wrong and why the "SECOND SET:" of console.log() commands won't execute.

È stato utile?

Soluzione

The parse routine returns Date objects, so your comparison is between two separate object instances. They'll never be == to each other.

Try:

if ($.datepicker.parseDate("mm/dd/yy", $("#dateOfAb").val().substring(0, 9)).getTime() == $.datepicker.parseDate("mm/dd/yy", $("#dateOfAb2").val().substring(0, 9)).getTime()) {

By comparing the results of calling .getTime(), you're comparing two numbers for equality, which will do what you want.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top