views:

298

answers:

5

The string can be got by getFullYear and so on.

Can it be done reversely?

+1  A: 
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
The MYYN
This is incorrect. Date.parse cannot handle `2009-1-1`. You'll have to replace `-` by `/`.
Jan Jongboom
+1  A: 
var s = "2010-1-10".split('-');
var dateObj = new Date(Number(s[0]),Number(s[1]) -1 ,Number(s[2]))
nemisj
+1  A: 
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 
Roland Bouman
fixed that for ya
Jan Jongboom
@Jan Jongboom, thanks!
Roland Bouman
+2  A: 

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

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

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

MSalters
Added code sample
Jan Jongboom
hey, that's real neat! great tip!
Roland Bouman
But it's a number,not object.
You can do `new Date(number)`
Jan Jongboom
A: 

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

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

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 an ISO string from a javascript Date is simplest 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;
}
kennebec