What type of date strings are these in JS?

Issue

I get a date string as Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time) from one place. I get it from 2021-09-17T11:50:59-04:00 in a second place.

I want to convert the first format to the second.

I am doing this in a crazy way, so I am thinking there must be a better one.

var d = new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`);
var iso = d.toISOString();
var time = d.toTimeString();

console.log(iso);
console.log(time);

var [date] = iso.split('T')
var [,localTime, timezone] = time.match(/([^ ]+) GMT([^ ]+)/);
var timezoneWithColon = timezone.replace(/(-*[0-9]{2,2})([0-9]{2,2})/,"$1:$2")

var desiredFormat = '2021-09-17T11:50:59-04:00';
var convertedFormat = `${date}T${localTime}${timezoneWithColon}`;
console.log(desiredFormat)
console.log(convertedFormat)
console.log(desiredFormat === convertedFormat);

The fiddle is over at https://jsfiddle.net/Dave_Stein/8tLv2g4j/.

Solution

2021-09-17T11:50:59-04:00 is an ISO-8601 date string.

toISOString should work, however it will convert the time to UTC. If you want this to format in your current timezone, you’ll have to use a library such as date-fns:

import { formatISO } from 'date-fns'

formatISO(new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`))

// prints '2021-09-17T11:50:59-04:00'

Answered By – user2029557

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published