Javascript Date.parse help

2019-02-23 12:41发布

I am using Javascript Date.parse() to check if a start time is after an end time.

The time in question is like this:

Date.parse("12:00pm") > Date.parse("9:30pm")

In Chrome this is coming up as false (as it should)

In IE it is incorrectly coming up as true.

The values Chrome see's are:

Thu Jul 22 2010 12:00:00 GMT-0400 (Eastern Daylight Time)
Thu Jul 22 2010 21:30:00 GMT-0400 (Eastern Daylight Time)

The values IE sees are:

Thu Jul 22 12:00:00 EDT 2010
Thu Jul 22 09:30:00 EDT 2010

How can I make IE work correctly?

update

OK this is only happening in IE7. Also I see now IE7 is not getting the am/pm which is stored in a SELECT box and retrieved via:

var startMerid = document.getElementById("start_time_ampm").options[document.getElementById("start_time_ampm").selectedIndex].value;

My select was like this:

<option>am</option>

but I changed to:

<option value="am">am</option>

and it now works.

3条回答
别忘想泡老子
2楼-- · 2019-02-23 12:51

The docs for Date.parse() in IE state the following:

If the 24-hour clock is used, it is an error to specify "PM" for times later than 12 noon. For example, "23:15 PM" is an error.

For a cross-browser solution, you should avoid parse() and parse the time string manually. Alternatively, you could use a cross-browser library for parsing dates/times - DateJS is a popular one.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-23 12:51

You can not just pass a time to Date.parse(), as it is expecting a datestring. If you flip the > in your code to a <, you'll notice it still returns false. This is because Date.parse() is returning NaN.

Try this:

var a = new Date("January 1, 1970 12:00:00");
var b = new Date("January 1, 1970 21:30:00");

if (a > b) { alert(true); } else { alert(false); }
if (a < b) { alert(true); } else { alert(false); }
查看更多
Anthone
4楼-- · 2019-02-23 12:55

What version of IE are you testing this on? IE8 correctly returns false for me.

查看更多
登录 后发表回答