JavaScript Date/Time Technical Reference Guide

Constructing a Date / Time
JavaScript Code Description Evaluated output
new Date() the current date and time (evaluated when the code is executed) Sun Jan 21 2024 03:03:00 GMT-0500 (Eastern Standard Time)
new Date(1705824180000) store a specific date and time in milliseconds(ms) since epoch1 Sun Jan 21 2024 03:03:00 GMT-0500 (Eastern Standard Time)
new Date("Jan 21, 2024")
store a specific date and time. because time is not specified, it will assume midnight in your local timezone. Sun Jan 21 2024 00:00:00 GMT-0500 (Eastern Standard Time)
new Date("Jan 21, 2024 13:00:59") store a specific date and time. unless a timezone is specified, it will assume you are specifying this in your local timezone.2 Sun Jan 21 2024 13:00:59 GMT-0500 (Eastern Standard Time)
new Date("Jan 21, 2024 13:00:59-08:00") store a specific date and time with a specific timezone offset.3 Here, You’re setting the time 8h behind UTC, which means the same time in EST(-5h from UTC) would be 3 hours ahead. Sun Jan 21 2024 16:00:59 GMT-0500 (Eastern Standard Time)
new Date("Jan 21, 2024 13:00:59Z") store a specific date and time in UTC (specified by the Z suffix) Sun Jan 21 2024 08:00:59 GMT-0500 (Eastern Standard Time)
new Date("2024-01-21T13:00:59")
new Date(2024,0,21,13,0,59,0)
store a specific date and time in ISO format: YYYY-MM-DDTHH:mm:ss.sssZ4. Note that when defining the date using numbers, not strings, the month is counted from a 0 index, meaning January is 0. Sun Jan 21 2024 13:00:59 GMT-0500 (Eastern Standard Time)
Parsing a Date

These methods allow you to extract a particular part of the date. Note that these have an equivalet “set” methods that allows you to set a single part of a date / time.

let now = new Date("Jan 21, 2024 13:00:59")

Note: the sample code below applies the methods to a variable now as an example, so you must have this variable defined as above first, before trying any of these code samples. In your own script, it may also not necessarily be a date object that represents ”now” — these methods can apply to any Date object you construct.

JavaScript Code Description Possible range Evaluated Output
now.getDate() numerical date 1–31 21
now.getDay() day of the week 0–6 (sun–sat) 0
now.getFullYear() full year 2024
now.getMonth() numerical month 0–11 0
now.getHours() hour 0–23 13
now.getMinutes() minutes 0–59 0
now.getSeconds() seconds 0–59 0
now.getMilliseconds() milliseconds 0–999 0
now.getTime() milliseconds since epoch 0– 2,147,483,647 1 1705860059000
now.getTimezoneOffset() difference from UTC in minutes5 -720 / +840 (UTC-12 to UTC+14) 300
Formatting and displaying the dates

These methods help you convert the date into a “string” data type, or a text format for displaying on the page. It can be combined with localization options in the section below. There 2 approaches to formatting dates: a) Using style shortcuts and b) Using explicit format instructions for each slice of time

let now = new Date("Jan 21, 2024 13:00:59")

A) When using shortcuts, you can remove either dateStyle or timeStyle keys in the options to only display a time or a date. The table below shows outputs for the same style shortcut applied to both date and time, but you can mix-and-match them as needed.

JavaScript Code style shortcut Evaluated Output
now.toLocaleString("en-US",{dateStyle: "full", timeStyle: "full"}) full Sunday, January 21, 2024 at 1:00:59 PM Eastern Standard Time
now.toLocaleString("en-US",{dateStyle: "long", timeStyle: "long"}) long January 21, 2024 at 1:00:59 PM EST
now.toLocaleString("en-US",{dateStyle: "medium", timeStyle: "medium"}) medium Jan 21, 2024, 1:00:59 PM
now.toLocaleString("en-US",{dateStyle: "short", timeStyle: "short"}) short 1/21/24, 1:00 PM

b) For more granular control of the format, you can specify options for each part of the Date/Time as follows. Note, you cannot use both a style shortcut as above and these granular options at the same time.


now.toLocaleDateString("en-US", {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric"
});

The table below illustrates how each date field might get formatted according to the style option provided. Empty cells indicate that the keyword is not a valid option for that date/time key.

date/time long short narrow numeric 2-digit
weekday Sunday Sun S
era Anno Domini AD A
year 2024 24
month January Jan J 1 01
day 21 21
hour 1 PM 01 PM
minute 0 0
second 59 59
timeZoneName Eastern Standard Time EST

** Note: These formatting keywords work in conjunction with the locale setting. The results above are from using the en-US (US English) setting. Using a different language/country locale will result in different outputs above.

Local and international formatting

These methods help you convert the date into formats specific to certain languages and countries, along with its timezone.
let now = new Date("Jan 21, 2024 13:00:59")

JavaScript Code description Evaluated Output
now.toISOString(); ISO4 date format (UTC)
YYYY-MM-DDTHH:mm:ss.sssZ
2024-01-21T18:00:59.000Z
now.toLocaleString(); timezone, language, and country of device. without arguments, the output depends on the implementation, the default locale, and the default time zone 1/21/2024, 1:00:59 PM
now.toLocaleString('mr-IN', {timeZone: 'Asia/Kolkata'}); Kolkata timezone, Marathi language format २१/१/२०२४, ११:३०:५९ PM
now.toLocaleString('en-IN', {timeZone: 'Asia/Kolkata'}); Kolkata timezone, English language format in India 21/1/2024, 11:30:59 pm
now.toLocaleString('de-DE', {timeZone: 'Europe/Berlin'}) Berlin timezone, German language format 21.1.2024, 19:00:59
now.toLocaleString("en-US", {timeZone: 'Europe/Berlin'}) Berlin timezone, English language format in US 1/21/2024, 7:00:59 PM

** Note: Using now.toLocaleString() without a locale (en-US) but with a timeZone option produces unexpected results. Always specify the locale if not using your local timezone. You can refer to this table for possible combinations of ISO language and country codes, with more details on the locales parameter on MDN. See list of timezones to see possible values for timeZone.

Comparing and operating on Dates

With Vanilla JavaScript, you can manipulate dates — get a time or day before and after a given date — through simple mathemetical subtraction or addition on the “epoch” millisecond representation of date.

  1. We convert the given date to ms via the .getTime() method.
  2. We calculate the ms of the duration we want to add/subtract. i.e. for xx hours, multiply xx by 60(min)*60(sec)*1000(ms), or for yy days, multiply yy by 24(hours)*60(min)*60(sec)*1000(ms).6
  3. We perform the operation — adding to get future times, subtracting to get past time.
  4. The result will be a numerical value in ms. In order to convert this back into a date, you will need to use the Date constructor on the value zz, using new Date(zz)

Example:
let date1 = new Date("Jan 01, 2024 13:00:30")
let date2 = new Date("Jan 02, 2024 14:30:50")

JavaScript Code Description Possible output Evaluated Output
date1 === date2 check if date1 and date2 are the same true / false false
date1 < date2 check if date1 is before date2 true / false true
date1 > date2 check if date1 is after date2 true / false false
date1 - date2 get the difference between the date1 and date2 in ms -90020000
date1 + date2 note: this will not do any meaningful operation on date objects — it will just concatenate the strings! 'Mon Jan 01 2024 13:00:30 GMT-0500 (Eastern Standard Time)Tue Jan 02 2024 14:00:50 GMT-0500 (Eastern Standard Time)'
date1.getTime() + 45*60*1000 add 45 minutes to date1, calculated in ms. we need to use another date constructor to convert the resulting ms back into a date format // new Date(1704134730000) evaluates to 'Mon Jan 01 2024 13:45:30 GMT-0500 (Eastern Standard Time)' 1704134730000

notes and caveats

  1. epoch refers to january 1, 1970, 00:00:00 UTC, a time arbitrarily chosen as “convenient” by Unix engineers. (Unix is a representation of time used in computing, stored in seconds. There is also a potential problem similar to “Y2K”, known as the the Year 2038 problem, with 32-bit computers storing time in the Unix format. The latest time that can be stored in 32bits is is 231 − 1 = 2,147,483,647 seconds after epoch, which is 03:14:07 on Tuesday, 19 January 2038. )
  2. browser behavior can be inconsistent in how it treats dates initialized without a timezone, so it is generally best to define time explicitly
  3. even though you may have stored the date/time given a particular timezone offset, the default way it will display to you will still be converted to your local timezone.
  4. the international standard iso 8601 lists time in the following order: year (yyyy), month (mm), day(dd), hour(hh), minutes(mm), seconds(ss), milliseconds(sss), and timezone offset(z, or +/- followed by hh:mm).
  5. note that this is the exception to the “native javascript tends to handle things in milliseconds” rule. the minute value is positive (+) if the local time zone is behind utc, and negative (-) if the local time zone is ahead of utc. because of daylight savings time, the timezone offset may vary based on the time of year.
    const nyOffsetSummer = new Date("2022-02-01").getTimezoneOffset(); // 300
    const nyOffsetWinter = new Date("2022-08-01").getTimezoneOffset(); // 240
  6. Calculating days after/before with this method will cause weirdness for places observing daylight saving time — when adding/subtracting time to get days in the future/past, keep in mind that some days of the year are 23 hours or 25 hours long! If you require a rigorous date management system, I recommend using date libraries below (each of them will have a different syntax) try to address these complexities.

Testing

To test how your time-based website is working, you can easily change your device time via your computer settings. However, to test other timezones, it’s easiest to use the browser’s developer tools. Below are instructions on how you might do this with Chrome.

  1. Click the three dots on the right edge of your Inspector Tools
  2. Open More Tools, and click Sensors
  3. The Sensors module will display at the bottom of your inspector, and you can change your location to another from the default list, or add custom locations.

JavaScript Libraries for robust Date Management

Further reading on JavaScript Time