Change ISO Date String to Date Object - JavaScript -
i stuck in weird situation , unfortunately,even after doing rnd , googling, unable solve problem.
i have date string in iso format, 2014-11-03t19:38:34.203z
, want convert date object new date()
method.
but when so, output is:
var isodate = '2014-11-03t19:38:34.203z'; console.log(new date(isodate)); //output is: tue nov 04 2014 01:08:34 gmt+0530 (ist)
the date passed of 3 nov,2014
, output 4 nov,2014
, it's because of gmt +5.30 of our local time(ist).
so, there generic method can date
object return date of nov 3,2014
.
note: don't have issues timestamp. can change time string 0 sethours()
method. thing want date
object new date()
having date of 3 nov,2014
.
do not pass strings date constructor, notoriously bad @ parsing strings. ie 8, one, not parse iso 8601 format strings @ , return nan. it's simple write own parser:
function parseisostring(s) { var b = s.split(/\d+/); return new date(date.utc(b[0], --b[1], b[2], b[3], b[4], b[5], b[6])); }
note if time 19:38:34.203 utc , timezone utc +0530, time in timezone 01:08:34 on following day, hence difference in dates. example, person on east coast of australia not observing daylight saving (i.e. utc +10), it's equivalent to:
4 november, 2014 05:38:34
edit
so if want return iso date, can use getiso* methods create whatever format suits, e.g.
function isoformatdmy(d) { function pad(n) {return (n<10? '0' : '') + n} return pad(d.getutcdate()) + '/' + pad(d.getutcmonth() + 1) + '/' + d.getutcfullyear(); } var s = '2014-11-03t19:38:34.203z'; var date = parseisostring(s); console.log(isoformatdmy(date)) // 03/11/2014
or use es5's toisostring:
parseisostring('2014-11-03t19:38:34.203z').toisostring(); // 2014-11-03t19:38:34.203z
a simple polyfill pre es5 browsers:
if (!date.prototype.toisostring) { date.prototype.toisostring = function() { var d = this; // padding functions function pad(n) {return (n<10? '0' : '') + n} function padd(n){return (n<100? '0' : '') + pad(n)} return d.getutcfullyear() + '-' + pad(d.getutcmonth() + 1) + '-' + pad(d.getutcdate()) + 't' + pad(d.getutchours()) + ':' + pad(d.getutcminutes()) + ':' + pad(d.getutcseconds()) + '.' + padd(d.getmilliseconds()) + 'z'; } }
Comments
Post a Comment