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?
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
                        I use date.js for all my non-human dating needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With