Problems during Date Time comparison in JavaScript
I have a scenario where i have to compare two DateTime objects
Start DateTime and End DateTime
- EndDatetime should be greater than StartDateTime
- 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 开发者_如何学Pythonis 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.
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).
精彩评论