Home > Software engineering >  How to change a date to a string without losing the original formatting?
How to change a date to a string without losing the original formatting?

Time:01-22

My date is 2022-01-19T13:00:56.000Z

I need to be able to replace some characters in this, so I need to convert it to a string.

However it loses its format if I use toString():

console.log(myDate.toString())
// output is Wed Jan 19 2022 21:00:56 GM  0800 (Hong Kong Standard Time)

I want to convert the date 2022-01-19T13:00:56.000Z to "2022-01-19T13:00:56.000Z".

How to accomplish this?

CodePudding user response:

toISOString DOES produce a string you can manipulate

const date = new Date("2022-01-19T13:00:56.000Z")
console.log(date.toLocaleString())

const isoString = date.toISOString()

console.log(isoString)

const ZPlus6 = isoString.replace("Z"," 0600")

console.log(ZPlus6)
console.log(new Date(ZPlus6))

  •  Tags:  
  • Related