Skip to content

Instantly share code, notes, and snippets.

@barbietunnie
Last active July 25, 2022 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barbietunnie/67d10b59f7716e3ff5892d70dd9a3cfa to your computer and use it in GitHub Desktop.
Save barbietunnie/67d10b59f7716e3ff5892d70dd9a3cfa to your computer and use it in GitHub Desktop.
Format JS Date in ISO-8601 without timezone issues
test.each`
dateStr | result
${'December 17, 1995 03:24:00'} | ${'1995-12-17'}
${'March 5, 1998 03:24:00'} | ${'1998-03-05'}
${'1995-12-17T03:24:00'} | ${'1995-12-17'}
${628021800000} | ${'1995-12-17'}
`('returns friendly date', ({ dateStr, result }) => {
expect(
getFriendlyDate(new Date(dateStr))
).toEqual(result)
})

Format JS Date in ISO-8601 without timezone issues

The following function provides an easy way to format Javascript dates in ISO-8601 format without using date.toISOString(), which could lead to timezone issues as the date is first converted to UTC which could lead to discrepancies in the result in certain timezones.

/**
 * Formats the provided date in _ISO-8601 format_ without using
 * `toISOString()` to avoid timezone issues
 *
 * @param date The Date object
 * @returns {string}
 */
function formatDate(date) {
    return [
        `${date.getFullYear()}`,
        `${date.getMonth() + 1}`.padStart(2, '0'),
        `${date.getDate()}`.padStart(2, '0')
    ].join('-')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment