Search code examples
javascriptjsonicalendar

How to get Date object from ISO Date string without dash(-) and colon(:) in Javascript


I was converting ICS to JSON, but it gave me date in the format like "20190103T073640Z", How to I get date object from this string in Javascript?

I know there are lots of answers for "how to convert ISO string to date object", but this string is missing dash and colon.

For e.g When I add dash and colonn, it gives output correctly

new Date("2019-01-03T07:36:40Z");

But how to get a date object in javascript from date string like this without dash and colons "20190103T073640Z"??

Edit for people who think this is duplicate - I have ICalendar file, I am using online converter to convert it to JSON, so the converter I am using giving out the date in that format which is not in the format which I can directly pass to new Date() to get a date object out of it. So is there any method which could parse "20190103T073640Z" string like this.

Thanks.


Solution

  • What about just extracting each date component, and creating a new Date object using the normal constructors?

    function parseIcsDate(icsDate) {
      if (!/^[0-9]{8}T[0-9]{6}Z$/.test(icsDate))
        throw new Error("ICS Date is wrongly formatted: " + icsDate);
      
      var year   = icsDate.substr(0, 4);
      var month  = icsDate.substr(4, 2);
      var day    = icsDate.substr(6, 2);
      
      var hour   = icsDate.substr(9, 2);
      var minute = icsDate.substr(11, 2);
      var second = icsDate.substr(13, 2);
      
      return new Date(Date.UTC(year, month - 1, day, hour, minute, second));
    }
    
    var date = parseIcsDate("20190103T073640Z");
    console.log(date);