Representing dates & times
Note:TheDate
object is now considered legacy and should be avoided in new code. We will update this page with modern alternatives soon.
Date object
JavaScript does not have a date data type. However, you can use theDate
object and its methods to work with dates and times in your applications. TheDate
object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.
JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since midnight at the beginning of January 1, 1970, UTC, with a Unix Timestamp being the number of seconds since the same instant. The instant at the midnight at the beginning of January 1, 1970, UTC is called theepoch.
TheDate
object range is -100,000,000 days to 100,000,000 days relative to the epoch.
To create aDate
object:
const dateObjectName = new Date([parameters]);
wheredateObjectName
is the name of theDate
object being created; it can be a new object or a property of an existing object.
CallingDate
without thenew
keyword returns a string representing the current date and time.
Theparameters
in the preceding syntax can be any of the following:
- Nothing: creates today's date and time. For example,
today = new Date();
. - A string representing a date, in many different forms. The exact forms supported differ among engines, but the following form is always supported:
YYYY-MM-DDTHH:mm:ss.sssZ
. For example,xmas95 = new Date("1995-12-25")
. If you omit hours, minutes, or seconds, the value will be set to zero. - A set of integer values for year, month, and day. For example,
xmas95 = new Date(1995, 11, 25)
. - A set of integer values for year, month, day, hour, minute, and seconds. For example,
xmas95 = new Date(1995, 11, 25, 9, 30, 0);
.
Methods of the Date object
TheDate
object methods for handling dates and times fall into these broad categories:
- "set" methods, for setting date and time values in
Date
objects. - "get" methods, for getting date and time values from
Date
objects. - "to" methods, for returning string values from
Date
objects. - parse and UTC methods, for parsing
Date
strings.
With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is agetDay
method that returns the day of the week, but no correspondingsetDay
method, because the day of the week is set automatically. These methods use integers to represent these values as follows:
- Seconds and minutes: 0 to 59
- Hours: 0 to 23
- Day: 0 (Sunday) to 6 (Saturday)
- Date: 1 to 31 (day of the month)
- Months: 0 (January) to 11 (December)
- Year: years since 1900
For example, suppose you define the following date:
const xmas95 = new Date("1995-12-25");
Thenxmas95.getMonth()
returns 11, andxmas95.getFullYear()
returns 1995.
ThegetTime
andsetTime
methods are useful for comparing dates. ThegetTime
method returns the number of milliseconds since the epoch for aDate
object.
For example, the following code displays the number of days left in the current year:
const today = new Date();const endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and monthendYear.setFullYear(today.getFullYear()); // Set year to this yearconst msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per daylet daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;daysLeft = Math.round(daysLeft); // Returns days left in the year
This example creates aDate
object namedtoday
that contains today's date. It then creates aDate
object namedendYear
and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days betweentoday
andendYear
, usinggetTime
and rounding to a whole number of days.
Theparse
method is useful for assigning values from date strings to existingDate
objects. For example, the following code usesparse
andsetTime
to assign a date value to theipoDate
object:
const ipoDate = new Date();ipoDate.setTime(Date.parse("Aug 9, 1995"));
Example
In the following example, the functionJSClock()
returns the time in the format of a digital clock.
function JSClock() { const time = new Date(); const hour = time.getHours(); const minute = time.getMinutes(); const second = time.getSeconds(); let temp = String(hour % 12); if (temp === "0") { temp = "12"; } temp += (minute < 10 ? ":0" : ":") + minute; temp += (second < 10 ? ":0" : ":") + second; temp += hour >= 12 ? " P.M." : " A.M."; return temp;}
TheJSClock
function first creates a newDate
object calledtime
; since no arguments are given, time is created with the current date and time. Then calls to thegetHours
,getMinutes
, andgetSeconds
methods assign the value of the current hour, minute, and second tohour
,minute
, andsecond
.
The following statements build a string value based on the time. The first statement creates a variabletemp
. Its value ishour % 12
, which ishour
in the 12-hour system. Then, if the hour is0
, it gets re-assigned to12
, so that midnights and noons are displayed as12:00
instead of0:00
.
The next statement appends aminute
value totemp
. If the value ofminute
is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value totemp
in the same way.
Finally, a conditional expression appends "P.M." totemp
ifhour
is 12 or greater; otherwise, it appends "A.M." totemp
.