Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active August 30, 2023 12:38
Show Gist options
  • Save ariesmcrae/a1a2f13e6741f20d001b9fedd45eda7d to your computer and use it in GitHub Desktop.
Save ariesmcrae/a1a2f13e6741f20d001b9fedd45eda7d to your computer and use it in GitHub Desktop.
Typescript: How to parse a UTC date using the date-fns library

Typescript: How to parse a UTC date using the date-fns library

Say you want to parse this date: 2023-05-31 T06:52:03Z. Note: This date is non-standard as it has a space between 31 and T

  // npm install date-fns date-fns-tz

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

  const dateObject: Date = parseISO("2023-05-31T06:52:03Z");
  const dateInUTC = utcToZonedTime(dateObject, 'UTC');

  // Format the date into UTC
  const formattedDateInUTC = utcFormat(dateInUTC, "yyyy-MM-dd_HH.mm.ss.SSS'Z'", { timeZone: 'UTC' });
  console.log(`formattedDateInUTC=${formattedDateInUTC}`) // 2023-05-31_06.52.03.000Z

  const year = dateObject.getUTCFullYear();
  const month = dateObject.getUTCMonth() + 1; // Months are 0-based
  const day = dateObject.getUTCDate();
  const hour = dateObject.getUTCHours();
  const minute = dateObject.getUTCMinutes();
  const second = dateObject.getUTCSeconds();
  const millisecond = dateObject.getUTCMilliseconds();

  console.log(`Year: ${year}`); // 2023
  console.log(`Month: ${month}`); // 5
  console.log(`Day: ${day}`); // 31
  console.log(`Hour: ${hour}`); // 6
  console.log(`Minute: ${minute}`); // 52
  console.log(`Second: ${second}`); // 3
  console.log(`Millisecond: ${millisecond}`); // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment