Skip to content

Instantly share code, notes, and snippets.

@RosanaRufer
Last active March 16, 2022 15:35
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 RosanaRufer/980e1f44b76962a0ad6b769f950f6dba to your computer and use it in GitHub Desktop.
Save RosanaRufer/980e1f44b76962a0ad6b769f950f6dba to your computer and use it in GitHub Desktop.
Dates in JavaScript

Day period

A day starts at 00:00:00 A day ends at 23:59:59.99

ISO Format

  • "YYYY-MM-DDTHH:mm:sss.sssZ"
  • Z means the date is in UTC

Creation with a string

  • new Date('2019-06-11') => Creates date in UTC
  • new Date('2019-06-11T00:00') => Creates date in local time zone

Creation with arguments

  • new Date(2019, 5, 11, 5, 23, 59) => Creates date in local time zone
  • new Date(2019, 5, 11, 5, 23, 59) => Creates date in local time zone
  • new Date(Date.UTC(2019, 5, 11)) => Creates a date in UTC

Creation with timestamp

  • Timestamp is milliseconds elapsed since Unix Epoch time
  • Unix Epoch time = January 1 1970 new Date(1560211200000) => ???

With no arguments

new Date() => Creates a date in local time

Weird bug

  const todayUTC = dateToUTC(new Date());
  // todayUTC 2022-03-16T00:00:00.000Z
  const daysAgo = new Date(todayUTC);
  // daysAgo 2022-03-16T00:00:00.000Z
  daysAgo.setDate(todayUTC.getDate() - x);
  // daysAgo 2 2021-04-09T23:00:00.000Z
  daysAgo.setHours(0, 0, 0, 0);
  // daysAgo 3 2021-04-09T23:00:00.000Z
  
const dateToUTC = (date: Date) => {
  return new Date(Date.UTC(
    date.getUTCFullYear(),
    date.getUTCMonth(),
    date.getUTCDate()
  ));
}
  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment