-2

I am trying to convert ISO time local time.

here is my code :

var local_date = new Date('2018-09-11T06:22:39.000-0400');
local_date.toLocaleDateString();
local_date.toLocaleTimeString();

this code is working fine in chrome but in IE its giving error. first line of code gives me Invalid Date

Looking for a fix which works in all browsers.

FYI: I do not want to use moment.js or any other library, want it in vanilla javascript.

Ram
  • 87
  • 2
  • 13

1 Answers1

1

So, the problem is your date-string format.

By reading the Mozilla documentation about the Date Object we can see that your string has to follow the IETF-compliant RFC 2822 timestamps and the ISO8601.

If we open the second one (the ISO8601) we can see that the accepted format is YYYY-MM-DDTHH:mm:ss.sssZ where the Z may be (+|-)HH:mm.

So instead of new Date('2018-09-11T06:22:39.000-0400'); if we execute new Date('2018-09-11T06:22:39.000-04:00'); it works.

If you don't want to add it manually, you can do it automatically by using the splice method from this answer and the code:

// A nice Polyfill
if (!String.prototype.splice) {
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

// Your code
var dateString = '2018-09-11T06:22:39.000-0400'.splice(26, 0, ":");
var local_date = new Date(dateString);
local_date.toLocaleDateString();
local_date.toLocaleTimeString();

I don't claim that 2018-09-11T06:22:39.000-0400 is in an invalid format, but an unaccepted by the IE.

Also, if you want to vanilla javascript you should stop opening IE at all.

Community
  • 1
  • 1
GramThanos
  • 3,572
  • 1
  • 22
  • 34