Reputation: 13
I have a timestamp in the following format:
[yyyy-MM-ddThh:mm:ssZ] (example: 2015-05-15T03:34:17Z)
I want's to parse this timestamp into Date and format is like: [Fri May 15 2015 09:04:17 GMT +5:30]:
Now, i am use the following code to parse and it work's fine in Firefox 3.6+ browsers. But the problem is, it's not working in internet explorer (IE) 8, in IE it returns 'NaN'.
var myDate = new Date(timestampDate);
//In Firefox i get myDate as Date object and i can get day, month and year. But in IE this myDate value is coming as NaN
var day = myDate.getDate();
var month = myDate.getMonth();
var year = myDate.getFullYear();
Any help is rewarded. Please give me a solution to make this working in IE also.
Upvotes: 1
Views: 1911
Reputation: 9926
I had the same problem and found this, supposing that you use jQuery UI:
$.datepicker.parseDate('yy-mm-dd', '2014-02-14');
This is a useful method of the UI Datepicker. I'm just about to write my own date parser to make my code jqui-independent but it may help others so I leave this answer here.
Upvotes: 0
Reputation: 11751
yyyy-MM-ddThh:mm:ssZ
is an ISO date. Browsers don't support them very well, FireFox doesn't parse 2015-05-15T03:34:17+01
for example.
You'll have to extract the elements out of the string manually before creating your date.
Upvotes: 0
Reputation: 104780
(function(){
//if the browser correctly parses the test string, use its native method.
var D= new Date('2011-06-02T09:34:29+02:00');
if(D && +D=== 1307000069000) Date.fromISO= function(s){
return new Date(s);
};
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
//extract the y-m-d h:m:s.ms digits:
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1; //adjust month
//create the GMT date:
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
// adjust for the timezone, if any:
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
})();
//test alert(Date.fromISO("2015-05-15T03:34:17Z").toUTCString())
Upvotes: 1