Javascript - String To Date - Php Iso String Format
Solution 1:
This code works in IE/Firefox/Chrome:
newDate("2010-11-30T08:32:22+0000".replace(/-/g,'/').replace(/T/,' ').replace(/\+/,' +'))
It changes 2010-11-30T08:32:22+0000
to 2010/11/30 08:32:22 +0000
and then creates the Date object from the fixed string.
I'm not sure if you should use this, it seems really dirty.
Solution 2:
Perhaps it is an overkill, but try Datejs
Solution 3:
This recipe doesn't take care of TimeZone. You need to hack it a little more to get it working with TZs. If you are sure that the time-zone is always +0000
, this code will work:
var s = "2010-11-30T08:32:22+0000";
// Replace non-digit characters with a space
s = s.replace(/\D/g," ");
// Split the string on spacevar date_parts = s.split(" ");
// subtract 1 from month to use in Date constructorvar yyyy = date_parts[0],
mm = date_parts[1] - 1,
dd = date_parts[2],
hh = date_parts[3],
mi = date_parts[4],
ss = date_parts[5];
// Now, the date_parts has year, month, date and so onvar dt = newDate(yyyy, mm, dd, hh, mi, ss);
This is a slightly verbose version of a recipe I have learned from JavaScript Cookbook
Solution 4:
New browsers version support new Date("2010-11-30T08:32:22+0000") (Chrome, FF4, IE9), but old browsers doesn't.
If timezone doesn't make sence (in cases when it always zero (your case) or omit), you can use this:
Date.fromISOString = (function(){
functionfastDateParse(y, m, d, h, i, s, ms){
returnnewDate(y, m - 1, d, h || 0, i || 0, s || 0, ms || 0);
}
// result functionreturnfunction(isoDateString){
return fastDateParse.apply(null, isoDateString.split(/\D/));
}
})();
If you need parse with timezone use this:
Date.fromISOString = (function(){
var tzoffset = (newDate).getTimezoneOffset();
functionfastDateParse(y, m, d, h, i, s, ms){ // this -> tzreturnnewDate(y, m - 1, d, h || 0, +(i || 0) - this, s || 0, ms || 0);
}
// result functionreturnfunction(isoDateString){
var tz = isoDateString.substr(10).match(/([\-\+])(\d{1,2}):?(\d{1,2})?/) || 0;
if (tz)
tz = tzoffset + (tz[1] == '-' ? -1 : 1) * (tz[3] != null ? +tz[2] * 60 + (+tz[3]) : +tz[2]);
return fastDateParse.apply(tz || 0, isoDateString.split(/\D/));
}
})();
Correct forms of date:
Date.fromISOString('2011-06-01');
Date.fromISOString('2011-06-01T00:00:00');
Date.fromISOString('2011-06-01T00:00:00Z');
Date.fromISOString('2011-06-01T00:00:00+30');
Date.fromISOString('2011-06-01T00:00:00-30');
Date.fromISOString('2011-06-01T00:00:00+0530');
Date.fromISOString('2011-06-01T00:00:00-0530');
Date.fromISOString('2011-06-01T00:00:00+05:30');
Date.fromISOString('2011-06-01T00:00:00-05:30');
// Your example valid as well.Date.fromISOString("2010-11-30T08:32:22+0000")
Solution 5:
var someDate = newDate("2010-11-30T08:32:22+0000");
I don't think it could be any simpler.
Post a Comment for "Javascript - String To Date - Php Iso String Format"