开发者

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 开发者_如何学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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜