Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two dates in JavaScript [duplicate]

Tags:

javascript

Possible Duplicate:
Compare dates with JavaScript

I have two dates, start date and end date. I am comparing them like this:

var fromDate = $("#fromDate").val();
var throughDate = $("#throughDate").val();

if (startdate >= enddate) {
    alert('start date cannot be greater then end date')
}

It gives the correct result... the only problem is when I compare the dates 01/01/2013 and 01/01/2014.

How can I correctly compare dates in JavaScript?

like image 333
user1657872 Avatar asked Dec 27 '22 18:12

user1657872


2 Answers

You can use this to get the comparison:

if (new Date(startDate) > new Date(endDate)) 

Using new Date(str) parses the value and converts it to a Date object.

like image 174
McGarnagle Avatar answered Dec 29 '22 08:12

McGarnagle


You are comparing strings. You need to convert them to dates first. You can do so by splitting your string and constructing a new Date

new Date(year, month, day [, hour, minute, second, millisecond])

Depending on you date format it would look like

var parts = "01/01/2013".split("/");
var myDate = new Date(parts[2], parts[1] - 1, parts[0]);
like image 38
Jasper de Vries Avatar answered Dec 29 '22 10:12

Jasper de Vries