Skip to content

Instantly share code, notes, and snippets.

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

Typescript: How to parse a unix epoch date using date-fns library

  // npm install date-fns date-fns-tz
  
  import { fromUnixTime, } from 'date-fns';
  import { utcToZonedTime, format as utcFormat } from 'date-fns-tz';

  // Unix epoch timestamp is a string in milliseconds in UTC
  const unixTimestampString = '1692761130000'; // 2023-08-23 03:25:30.000Z

  const unixTimestamp = Number(unixTimestampString);

  const dateObject = fromUnixTime(unixTimestamp / 1000); // Divide by 1000 to get seconds
  const dateInUTC = utcToZonedTime(dateObject, 'UTC');

  const formattedDateInUTC = utcFormat(dateInUTC, "yyyy-MM-dd_HH.mm.ss.SSS'Z'", { timeZone: 'UTC' });
  console.log(`formattedDateInUTC=${formattedDateInUTC}`) // 2023-08-23_03.25.30.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}`); // 8
  console.log(`Day: ${day}`); //23
  console.log(`Hour: ${hour}`); // 3
  console.log(`Minute: ${minute}`); // 25
  console.log(`Second: ${second}`); // 30
  console.log(`Millisecond: ${millisecond}`); // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment