0

I'm trying to format an string date that looks like this:

Tue Mar 13 2018 00:00:00 GMT-0600 (Mountain Daylight Time)}

to:

"2018-03-13T00:00:00",

Can anyone tell me what I'm missing or need to add? Thanks a lot in advance!

let someDate = 'Tue Mar 13 2018 00:00:00 GMT-0600 (Mountain Daylight Time)}';

console.log(someDate.replace(/T.+$/, "T00:00:00"));
Devmix
  • 1,599
  • 5
  • 36
  • 73
  • 1
    Be aware removing the time zone is a very bad idea. It can mean any other tool using the date, will be off by a day. – enf0rcer Dec 13 '18 at 19:26

2 Answers2

0

let someDate = 'Tue Mar 13 2018 00:00:00 GMT-0600 (Mountain Daylight Time)';

console.log(new Date(someDate).toISOString().replace(/T.+$/, "T00:00:00"));
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
  • @RobG removing the timezone is part of the requirements - I made the assumption that the date is parsed in the same timezone that the date string was created, in which case the date is not changed. – ic3b3rg Dec 13 '18 at 20:44
  • In `new Date(Date.parse(someDate))`, *Date.parse* is redundant. The **only** timezone where this does not change the Date is GMT. In my timezone, it represents 16:00 on 13 March but the string appears as 00:00:00. – RobG Dec 13 '18 at 20:46
  • @RobG you're correct that `Date.parse` is unnecessary - thank you, I updated my answer. You're incorrect about the date changing - test by changing the date string to reflect your time zone. My comment about removing the timezone was in reference to your earlier comment about my answer not being a good solution, which you have since deleted. – ic3b3rg Dec 13 '18 at 20:56
  • It's still not a good solution as it will change the date for the period within the local timezone offset of midnight, and will always change the time if the local timezone is not GMT. You're just hard coding it to 0000h. – RobG Dec 13 '18 at 22:10
  • @RobG That is incorrect - test it with a date string in your time zone – ic3b3rg Dec 13 '18 at 22:13
  • `Tue Mar 13 2018 00:00:00 GMT-0600` will be parsed as 2018-03-13 06:00 UTC (presuming it's parsed correctly). If the time in the timestamp is say 20:00:00 (i.e. Tue Mar 13 2018 20:00:00 GMT-0600), it will be 2018-03-14 02:00:00 UTC and the above will return 2018-03-14T00:00:00. So it's changed the date and the time (which is inevitable since you're hard coding the time). – RobG Dec 13 '18 at 22:21
0

someDate.toISOString() will give you the date in ISO format