0

We are using this date format in our app: 2021-03-20T15:42:02+01:00, but I can't make it with pure javascript.

In the past we used moment.js, but I want to avoid it.

In moment, the syntax was the following:

moment().format()
//output: 2021-03-20T15:59:13+01:00

this was the closest to what I found in pure js...

new Date().toISOString()
//output: 2021-03-20T14:59:13.595Z

Is there an "easy" way to achieve the same format as above?

Pejman Kheyri
  • 4,044
  • 9
  • 32
  • 39
Gyarmati István
  • 503
  • 1
  • 5
  • 8

1 Answers1

0

For the date/time parts the safest is to just build the string from its individual components using the Date get methods, and for the UTC offset suffix, you would get the time zone offset, and turn that into hh:mm format:

function localeFormat(date) {
    var offsetMinutes = date.getTimezoneOffset();
    var offset = Math.abs(offsetMinutes);
    return (date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDay()
         + "T" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()
        + (offsetMinutes > 0 ? "-" : "+")
        + Math.floor(offset/60) + ":" + Math.abs(offset % 60)
        ).replace(/(\D)(\d)(?!\d)/g, "$10$2");
}

console.log(localeFormat(new Date()));

Tested on IE9, 10 and 11, current Edge, Firefox and Chrome versions.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • This is the method detailed in this [answer](https://stackoverflow.com/a/51643788/13762301) from the flagged duplicate. – pilchard Mar 20 '21 at 20:25
  • That answer does not deal with the offset suffix ("+01:00"), @pilchard, which is specific to this question. – trincot Mar 20 '21 at 20:30