When assigning a date without specifying the time zone, JavaScript defaults to the browser’s time zone.
When retrieving a date without specifying the time zone, the result is adjusted to the browser’s time zone.
In simpler terms, if a date/time originates in GMT (Greenwich Mean Time), it will be adjusted to CDT (Central US Daylight Time) when accessed by a user browsing from the central US.
Dates in short format are typically expressed using the “MM/DD/YYYY” syntax, as demonstrated below:
Example
const d = new Date(“03/25/2015”); |
An error may occur in certain browsers when months or days lack leading zeroes.
const d = new Date(“2015-3-25”); |
The behavior of “YYYY/MM/DD” is undefined.
Certain browsers may attempt to interpret the format, while others may return NaN.
const d = new Date(“2015/03/25”); |
The behavior of “DD-MM-YYYY” is also undefined. Some browsers may attempt to interpret the format, while others may return NaN.
const d = new Date(“25-03-2015”); |
Long dates are typically expressed using a “MMM DD YYYY” syntax, such as this:
Example
const d = new Date(“Mar 25 2015”); |
The order of the month and day can vary:
Example
const d = new Date(“25 Mar 2015”); |
Additionally, the month can be written in full (January) or abbreviated (Jan).
Example
const d = new Date(“January 25 2015”); |
Example
const d = new Date(“Jan 25 2015”); |
Commas are ignored, and names are case-insensitive.
Example
const d = new Date(“JANUARY, 25, 2015”); |
With a valid date string, you can utilize the Date.parse() method to convert it into milliseconds.
Date.parse() returns the number of milliseconds between the given date and January 1, 1970.
Example
let msec = Date.parse(“March 21, 2012”); |
Subsequently, you can utilize the number of milliseconds to create a date object.
Example
let msec = Date.parse(“March 21, 2012”); const d = new Date(msec); |