JS Dates
May 22, 2020 by Jane

Creation: (*The computed date will be relative to your time zone, if unspecified, JS uses the browser's time zone)

1) Default:  new Date() or Date.now() will return ms since 1970 Jan 1

2) Custom human-readable: new Date(yr, mon, day, hr, min, sec, ms) - the year and month are required, rest can be omitted

  • the year can be 4 digits or 2 digits (1900 will be assumed)
  • the month can be 0 - 11

3) Custom milliseconds: new Date(ms since 1970 Jan 1) - the milliseconds can be negative

4) From string: new Date([date_string])

  • E.g. new Date("October 13, 2014 11:13:00");
  • From ISO format YYYY-MM-DD - new Date("2015-03-25");

 

Format:

1) toString() - also the default method.

  • Converts to [Day_of_week], MMM DD YYYY HH:MM:SS [Time Zone Code]  [Time Zone]
  • E.g. "Fri May 22 2020 03:46:58 GMT-0700 (Pacific Daylight Time)"

2) toUTCString()

  • Converts to [Day_of_week], DD MMM YYYY HH:MM:SS [Time Zone Code]
  • E.g. "Fri, 22 May 2020 10:48:41 GMT"

3) toDateString() - shorter and more day-to-day version

  • Converts to [Day_of_week] MMM DD YYYY
  • E.g. "Fri May 22 2020"

 

Commonly used accessors:

  • getFullYear() - return YYYY
  • getMonth() - return MM (0 - 11)
  • getDate() - return day as number (1 - 31)
  • getDay() - return day of week (0 - 6)
  • getHours - return hour (0 - 23)
  • getMinutes() - return minutes (0 - 59)
  • getSeconds() - return second (0 - 59)
  • getMilliseconds - return ms (0 - 999)
  • getTime() - return ms since 1970 Jan 1

 

* These accessors all have corresponding setters to set the full year, month, day etc.

  • setFullYear can also set month and day E.g. setFullYear(2020, 11, 3);
  • If the parameter is not within range E.g. setMonth(13) the overflow will flow into the year automatically, similarly a negative value can be use to set the time to the past

More info: https://www.w3schools.com/js/js_date_formats.asp