0

Can someone please help me understand why this set of functions always calculates the date a day behind?

const parseISOString = (isoStr) => {
  return new Date(Date.parse(isoStr))
}

const formatDt = () => {
  const dtInISOFmt = "2019-12-01T05:00:00.000+00:00"
  const dateStrParts = parseISOString(dtInISOFmt).toDateString().split(" ")
  const month = dateStrParts[1]
  const day = dateStrParts[2]
  const year = dateStrParts[3]
  return [day, month, year].join(" ")
}

console.log(`formatDt(): ${formatDt()}`)

Here's a quick plunkr with the same: https://plnkr.co/edit/X3EkEZM6uNDPA36w

Quick background: Was trying to do some basic date formatting/parsing without importing any major date formatting JS libraries (e.g. moment) into my application, to reduce it's size / footprint.

Any and all help much appreciated.

Thanks in advance!

sukhadia
  • 11
  • 3
  • 1
    `toDateString` uses your own timezone... Not UTC. Use `toUTCString` instead. – trincot Dec 15 '20 at 20:14
  • Thanks @trincot! That did the trick. – sukhadia Dec 15 '20 at 20:19
  • The use of *Date.parse* in `new Date(Date.parse(isoStr))` is entirely redundant, the result will be identical to `new Date(isoStr)`. – RobG Dec 15 '20 at 21:48
  • Also see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Dec 15 '20 at 22:35

0 Answers0