0

new Date().toISIOString() or toJSON() provide an unambiguous Date and Time and TimeZone Offset:

"2021-10-07T13:52:14.333Z"

I want the same formatting, or very similar, but without the restriction to UTC :

"2021-10-07T14:52:14.333+0100"

Is there a built-in solution that doesn't involve 20 lines of code and battery of unit tests for edge cases?

The timezone offset seems the tricky thing. Things I've looked at don't seem to offer a 'show the timezone offset' option, only timezone names.

  • toLocaleString()
  • Intl.DateTimeFormat()
  • Intl.DateTimeFormat().formatToParts()

for example, Intl.DateTimeFormat().resolvedOptions() knows:

calendar: "gregory"
day: "2-digit"
locale: "en-GB"
month: "2-digit"
numberingSystem: "latn"
timeZone: "Europe/London"
year: "numeric"

but to know what time "1st April 2020 12:00 Europe/London" was, requires a world history lookup table of when daylight saving starts and ends.

Chris F Carroll
  • 11,146
  • 3
  • 53
  • 61
  • 1
    Funny as your question is, there's [the native JS way](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) or a library like [moment.js](https://github.com/moment/moment/), [date.format](https://stevenlevithan.com/assets/misc/date.format.js), etc... I wouldn't roll my own date formatting any more than I'd roll my own authentication. – D M Oct 07 '21 at 14:23
  • 1
    Of note: the moment.js team has [recommendations](https://momentjs.com/docs/#/-project-status/recommendations/) for libraries based on modern browser features. – D M Oct 07 '21 at 14:29
  • I did look at the first page of https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date and I couldn't quite see an answer to my question, unless, “No. Use a 3rd party library” is the answer. Yes there are many many previous SO qs on js dates. Not many of them seem fussed about timezone offset, tho it seems to me quite helpful. – Chris F Carroll Oct 07 '21 at 14:38
  • It's definitely not the same question and your use case certainly seems like something that should be easily doable with native JS in 2021. My gut still says, "library", though. Call it cynicism, I guess. – D M Oct 07 '21 at 14:39

0 Answers0