Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active September 11, 2023 01:17
Show Gist options
  • Save ariesmcrae/cd678f6d019f2b57ddcb747f819e5595 to your computer and use it in GitHub Desktop.
Save ariesmcrae/cd678f6d019f2b57ddcb747f819e5595 to your computer and use it in GitHub Desktop.
Typescript: Convert current date object to UTC string using the 'date-fns-tz' library

Typescript: Convert current date object to UTC string using the 'date-fns-tz' library

// npm i date-fns-tz

import { utcToZonedTime, format as utcFormat } from 'date-fns-tz'

const main = async (): Promise<void> => {
  const dateInUtc: Date = utcToZonedTime(new Date(), 'UTC')
  const formattedDateInUTC = utcFormat(dateInUtc, 'yyyy-MM-dd\'T\'HH:mm:ss\'Z\'', { timeZone: 'UTC' })
  console.log(`formattedDateInUTC=${formattedDateInUTC}`) //example output: 2023-09-11T10:48:28Z
}

;(async () => {
  await main()
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment