IE JavaScript date parsing error

帅比萌擦擦* 提交于 2019-11-26 22:57:57
Jitendra

You are getting NaN value in IE 8 and its working in Firefox because the format of the string varies with browser and operating system.

For example, in IE6 for Windows XP, the string is in the following format:

Tue Dec 05 16:47:20 CDT 2006

But in Firefox for Windows XP, the string is

Tue Dec 05 2006 16:47:20 GMT-0500

to make it compatible with both browser you will have to first check the browser in your javascript code and then accordingly give your input date string.

Brian Ellis

I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.

You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:

$.datepicker.parseDate('yy-mm-dd', '2007-01-26');

Is solved my problem by creating an date object and let me give it back the timestamp. But for this you need to convert you string into this format:

year, month, date, hours, minutes, seconds,ms

an example would be like:

dateObj = new Date(year, month, date);
timestamp = dateObj.getTime();

This works save in IE and FF.

IE Dev Center: Date Object (JavaScript)

Mozilla Dev Network: Date

For your example you would to something like this:

//your string
var str = "Fri Jun 11 04:55:12 +0000 2010";
//maps months to integer from 0 to 11
var monthArray = {"Jan":0, "Feb":1, "Mar":2, "Apr":3, "May":4, "Jun":5, "Jul":6, "Aug":7, "Sep":8, "Oct":9, "Nev":10, "Dec":11};
//get the values from the string
var regex = /^[^ ]+ ([^ ]+) (\d{1,2}) (\d{2}):(\d{2}):(\d{2}) \+(\d{4}) (\d{4})$/;
match = regex.exec(str);
var month   = monthArray[match[1]],
    date    = match[2],
    hours   = match[3],
    minutes = match[4],
    seconds = match[5],
    ms      = match[6],
    year    = match[7];

//create date object with values
var dateObject = new Date(year, month, date, hours, minutes , seconds, ms);

var ts = dateObject.getTime(); //timestamp in ms

because of the +00000. try to add that the last

var d = Date.parse("Fri Jun 11 04:55:12 2010 +0000");
superwhatever

This may help you. I just solved a problem similar to this.

Problem with Javascript Date function in IE 7, returns NaN

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!