user632323
user632323

Reputation: 29

Problems during Date Time comparison in JavaScript

I have a scenario where i have to compare two DateTime objects

Start DateTime and End DateTime

  1. EndDatetime should be greater than StartDateTime
  2. EndDateTime should be greater than CurrentTime

Now i am trying with simple code as suggested in many of sites and blogs, using ">" or "<" symbols. E.g: if((Date.parse(startdate)) > (Date.parse(enddate))) { alert("Please enter enddate greater than startdate"); }

This works fine if DateTime is in same Month. Even after entering valid datetime range like start datetime being Feb 20th 2011 and End datetime being March 3rd 2011, i still get above alert which is actually wrong.

Can anyone please help, in figuring what is wrong or any one who can provide JS function to compare two DateTime objects.

Thanks.

Upvotes: 0

Views: 1324

Answers (1)

inkredibl
inkredibl

Reputation: 1993

You should use ".getTime()" to get the timestamp integer and then comparing those.

if(Date.parse(startdate).getTime() > Date.parse(enddate).getTime())
{
  alert("Please enter enddate greater than startdate");
}

My guess is that when you try to compare the objects themselves, only their string representations get compared lexicographically (not 100% sure about this though).

Upvotes: 1

Related Questions