randomizertech
randomizertech

Reputation: 2329

Compare dates with specified format in Javascript

I have two dates in format 14-May-2013 and 15-Jun-2013

How can I compare this two dates?

This is the code I have, but it doesn't seem to be working fine.

if (col == 8 && m == 2) {
    var firstValue = document.getElementById(tableID+m+""+6).innerHTML.split('-');
    var secondValue = document.getElementById(tableID+m+""+7).innerHTML.split('-');

    var firstDate=new Date();
    firstDate.setFullYear(firstValue[0],firstValue[1], firstValue[2]);

    var secondDate=new Date();
    secondDate.setFullYear(secondValue[0],secondValue[1], secondValue[2]);     

    if (firstDate < secondDate) 
    {
        alert("First Date  is less than Second Date");
    }
    else
    {
        alert("Second Date  is less than First Date");
    }   
}

What am I doing wrong and how do I make it work right?

Thanks!

Upvotes: 0

Views: 130

Answers (3)

Bergi
Bergi

Reputation: 664434

format 14-May-2013 and 15-Jun-2013

firstDate.setFullYear(firstValue[0],firstValue[1], firstValue[2]);

What am I doing wrong?

setFullYear does not take month names or abbreviations. You will have to parse your date format to get the month number first.

function parse(str) {
    var vals = str.split('-');
    return new Date(
        +vals[0],
        ["jan","feb","mar","apr","may","jun","jul","aug","sep",
         "oct","nov","dez"].indexOf(vals[1].toLowerCase()),
        +vals[2]
    );
}
var firstDate = parse(document.getElementById(tableID+m+""+6).innerHTML)
var secondDate = parse(document.getElementById(tableID+m+""+7).innerHTML);
if (firstDate < secondDate) {
    alert("First Date  is less than Second Date");
} else {
    alert("Second Date  is less than or equal to First Date");
}

Upvotes: 2

Mark Walters
Mark Walters

Reputation: 12390

Change to this

if(firstDate.getTime() < secondDate.getTime()){
  //do something
} else {
  //do something else
}

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC

So you are basically comparing two Millisecond representations of the date.

Upvotes: 1

JonnyS
JonnyS

Reputation: 314

When I compare two I transform the time into Unix time. The results are much more reliable. In javascript this would be the getTime() function.

So for you firstDate.getTime() < secondDate.getTime().

http://www.tutorialspoint.com/javascript/date_gettime.htm

Upvotes: 1

Related Questions