views:

120

answers:

2

Hi, I am learning javascript and I am trying to figure out if there is a simple way to convert a standard formatted Date to ISO8601 format (YYYY-MM-DDThh:mm:ssTZD). Advices?

+4  A: 

I use date.js for all my non-human dating needs.

Diodeus
Nice link, thanks. Bookmarked for future reference.
Gianluca
+3  A: 

If you mean by "standard formatted date" a date string in the IETF standard format (i.e.: 'Thu, 15 Oct 2009 12:30:00 GMT') that is acceptable by the Date.parse function and by the Date constructor, you can parse the date and write a simple helper function to return an ISO8601 date, using a Date object as input:

function ISODateString(d){

  function pad(n){
    return n<10 ? '0'+n : n;
  }

  return d.getUTCFullYear()+'-'
    + pad(d.getUTCMonth()+1)+'-'
    + pad(d.getUTCDate())+'T'
    + pad(d.getUTCHours())+':'
    + pad(d.getUTCMinutes())+':'
    + pad(d.getUTCSeconds())+'Z'
}


var d = new Date('Thu, 15 Oct 2009 12:30:00 GMT');
console.log(ISODateString(d)); // 2009-10-15T12:30:00Z
CMS
This seems the clear and simple solution I've been looking for. Thank you sir.
Gianluca