Home > Software engineering >  Javascript: Format Date and what type of date is it
Javascript: Format Date and what type of date is it

Time:03-30

How do I format a javascript date to the following format:

2022-02-23T17:04:05.6474089-05:00

javascript

CodePudding user response:

Its ISO 8601 format

You can use Date.prototype.toISOString()

toISOString returns an UTC time. If you want to include the time offset you can use moment for that, passing true for keepOffset param:

console.log(moment().toISOString(true))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

CodePudding user response:

In ISO Z is equivalent to 00:00. JS implementations nowadays always return UTC (Z) so this code is safe for an input of instance Date.

const d = new Date()

const toAVerySpecificFormat = (date) => {
  return date.toISOString().replace(/Z$/, "0000 00:00")
}

console.log(toAVerySpecificFormat(d))

  • Related