Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date to IS8601 format?

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?

like image 976
gbr Avatar asked Dec 22 '22 08:12

gbr


2 Answers

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
like image 133
Christian C. Salvadó Avatar answered Jan 05 '23 18:01

Christian C. Salvadó


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

like image 20
Diodeus - James MacFarlane Avatar answered Jan 05 '23 16:01

Diodeus - James MacFarlane