javascript - compare dates in different formats

10,344

Solution 1

Without using a 3rd party library, you can create new Date objects using both those formats, retrieve the number of milliseconds (since midnight Jan 1, 1970) using getTime() and then simply use >:

new Date("2013/08/26").getTime() > new Date(1381308375118).getTime()

Solution 2

I strongly recommend using datejs library.

Thus this can be written in one single line:

Date.today().isAfter(Date.parse('2013/08/26'))

Solution 3

I would make sure that I am comparing the "date" element of each format and exclude any "time" element. Then with both dates converted to milliseconds, simply compare the values. You could do something like this. If dates are equal it returns 0, if the first date is less that the second then return -1, otherwise return 1.

Javascript

function compareDates(milliSeconds, dateString) {
    var year,
        month,
        day,
        tempDate1,
        tempDate2,
        parts;

    tempDate1 = new Date(milliSeconds);
    year = tempDate1.getFullYear();
    month =  tempDate1.getDate();
    day = tempDate1.getDay();
    tempDate1 = new Date(year, month, day).getTime();

    parts = dateString.split("/");
    tempDate2 = new Date(parts[0], parts[1] - 1, parts[2]).getTime();

    if (tempDate1 === tempDate2) {
        return 0;
    }

    if (tempDate1 < tempDate2) {
        return -1;
    }

    return 1;
}

var format1 = 1381308375118,
    format2 = "2013/08/26";

console.log(compareDates(format1, format2));

On jsfiddle

Share:
10,344

Related videos on Youtube

Tom
Author by

Tom

Web designer and wannabe developer (I'm learning... constantly)

Updated on September 18, 2022

Comments

  • Tom
    Tom over 1 year

    I have 2 dates which I need to compare to see if one is greater than the other but they are in different formats and I'm not sure of the best way to compare the 2.

    The formats are:

    1381308375118 (this is var futureDate)

    which is created by

    var today = new Date(); today.setHours(0, 0, 0, 0); var futureDate = new Date().setDate(today.getDate() + 56); //56 days in the future...

    And the other format is

    2013/08/26

    Any ideas how I can compare the 2?

  • Castrohenge
    Castrohenge over 10 years
    Why the downvote? I've only test in FF and IE9, but it seems like a valid way to compare dates, unless I've missed something.
  • Xotic750
    Xotic750 over 10 years
    You are comparing Date objects not the actual dates
  • Castrohenge
    Castrohenge over 10 years
    Ahh ok. Modified to retrieve the millisecond value for each date.