How to convert string 2010-1-10 to date object in javascript?

String can be obtained by getFullYear, etc.

Is it possible to do the opposite?

+7
javascript date
source share
6 answers

Replace - with / , and JavaScript can parse it. Stupid mistake in JS specification (ISO date and time standard is very clear that - correct)

 var str = "2010-1-10"; alert(Date.parse(str.replace(/-/g,"/"))); 

Try pasting it into your browser: javascript:alert(Date.parse("2010-01-01".replace(/-/g,"/")));

+16
source share
 var s = "2010-1-10".split('-'); var dateObj = new Date(Number(s[0]),Number(s[1]) -1 ,Number(s[2])) 
+8
source share
 var date = new Date(); var str = "2010-1-10"; var dateArray = str.split("-") date.setFullYear(parseInt(dateArray[0])); date.setMonth(parseInt(dateArray[1])-1); // months indexed as 0-11, substract 1 date.setDate(parseInt(dateArray[2])); // setDate sets the month of day 
+1
source share
 Date.parse(datestring) 

Example; Return the number of milliseconds from January 1, 1970 to July 8, 2005:

 var d = Date.parse("Jul 8, 2005"); alert(d); // 1120773600000 
0
source share

To return a new Date object from a string of any ISO 8601, which can range from "2010-01-10" to "2010-01-10T19: 42: 45.5-05-05: 00, several templates need to be considered.

The division of seconds (preceded by a decimal point) and the local offset TimeZone (preceded by "+" or "-") are three quarters of the code:

 Date.parseISO= function(iso){ var z, tem, TZ, ms= 0; z= /:/.test(iso)? ' GMT': ''; ms=/(\.\d+)/.exec(iso); if(ms){ ms= ms[1]; iso= iso.replace(ms,''); ms= Math.round(1000*ms); } if(z && !/Z$/.test(iso)){ TZ=/:\d\d((\-|\+)(\d\d):(\d\d))$/.exec(iso); if(TZ){ tem= TZ[3]*60+(+TZ[4]); z+= TZ[2]+tem; iso= iso.replace(TZ[1],''); } } iso= iso.replace(/[^\d:]/g,' ')+z; var stamp= Date.parse(iso); if(!stamp) throw iso +' Unknown date format'; return new Date(stamp+ms); } 

// Getting the ISO string from javascript Date is the easiest if you use UTC (GMT)

 Date.prototype.toISO= function(time){ var i=0, D= this, A= [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(), D.getUTCMinutes(), D.getUTCSeconds()]; ++A[1]; var T= A.splice(3); A= A.join('-'); if(time){ if(time==2) T.pop(); while(i< T.length){ if(T[i]<10) T[i]= '0'+T[i]; ++i; } if(time==4)T[2]= T[2]+'.'+ Math.round((this.getMilliseconds()/1000)*1000); return A+'T'+T.join(':')+'Z'; } return A; } 
0
source share
 console.log(new Date('2010-01-10')); 
0
source share

All Articles