user14476434
user14476434

Reputation:

Getting time in ISO 8601 without dash/hyphen

Right now the date is coming out as:

2020-11-12T19:11:00.000Z

Is there any way to get it as 20201112T191100Z? Basically without the hyphens/colons/period.

I'm getting the date by converting the current format of

2020-11-12 11:11:00 

to

2020-11-12T19:11:00.000Z

using

new Date('2020-11-12 11:11:00').toISOString()

I was hoping there'd be a simpler way of formatting it as desired without just splicing/deleting it like a normal string.

Thanks for any help!

Upvotes: 2

Views: 1878

Answers (1)

iAmOren
iAmOren

Reputation: 2804

You could split and join, slice and concat:

ISODateNoDashesNoColonsNoDecimalNoMilliseconds = 
new Date('2020-11-12 11:11:00').toISOString()
  .split("-").join("")
  .split(":").join("")
  .slice(0,15).concat("Z");

Or replace using RegExp:

ISODateNoDashesNoColonsNoDecimalNoMilliseconds = 
new Date('2020-11-12 11:11:00').toISOString()
  .replace(/-|:/g, "")
  .replace(/\.\d{3}Z/, "Z");

Or split and join, slice and +:

ISODateNoDashesNoColonsNoDecimalNoMilliseconds = 
new Date('2020-11-12 11:11:00').toISOString()
  .split("-").join("")
  .split(":").join("")
  .slice(0,15)+"Z";

Or replaceAll, slice and +:

ISODateNoDashesNoColonsNoDecimalNoMilliseconds = 
new Date('2020-11-12 11:11:00').toISOString()
  .replaceAll("-", "")
  .replaceAll(":", "")
  .slice(0,15)
  +"Z";

Upvotes: 3

Related Questions