The Date
is another built-in object in JavaScript. We used it in the development of the SleepTime App. Here is a summary of its operations. For a more detailed reference, visit MDN web docs.
Date measured in “milliseconds” (adjusted for leap seconds) since the “epoch” (midnight of January 1, 1970 UTC).
You can pass milliseconds to the constructor; valid range ±100,000,000 days from epoch.
Caution: Dates are converted to numbers in arithmetic expressions.
You can pass the following parameters to Date()
constructor to create a specific date:
year
,zeroBasedMonth
,day
,hours
,minutes
,seconds
,milliseconds
The parameters must be provided in order, and everything starting from “day” are optional.
Caution: Out-of-range zeroBasedMonth, day, hours, etc. silently roll.
For UTC, construct with date string in format YYYY-MM-DDTHH:mm:ss.sssZ (with literal T, Z):
Caution: Other string formats may be accepted by the constructor, but their format is not standardized.
Caution: Date(...)
without new
constructs string (in non-standard format).
Date.now()
is the current date/time, but it yields milliseconds, not a Date object.
A very useful static function is Date.parse(dateString)
. It also yields milliseconds, but you can pass that to the Date constructor to get a Date object.
Caution: support for dateString
in YYYY-MM-DDTHH:mm:ss.sssZ
format is guaranteed. Support for other formats are implementation-dependent.
Another useful static function is Date.UTC(year, zeroBasedMonth, day, hours, minutes, seconds, milliseconds)
where arguments after year
are optional.
The Date object has traditional getter/setter methods getHours
/setHours
.
For UTC, there are UTC variants getUTCFullYear
, setUTCFullYear
, getUTCMonth
, setUTCMonth
, and so on.
toISOString
yields string in YYYY-MM-DDTHH:mm:ss.sssZ
format.
toString
, toDateString
, toTimeString
yield “humanly readable” string in local time zone, or only the date/time portion:
toUTCString
yields “humanly readable” string in UTC:
toLocaleString
, toLocaleDateString
, toLocaleTimeString
yield localized string: