JavaScript Date Object

This YouTube video was created by Steve Griffith.

The JavaScript Dateopen in new window object can be used to work with dates and time within a JavaScript program. A Date object contains a number that represents the milliseconds since the Unix Epoch or January 1, 1970.

Create a New Date Object

A new date object can be created by using the Date()open in new window constructor. Like with all constructors, the new keyword must also be used.

const d = new Date()

The Date() constructor can take different parameters, which are used to determine the single moment in time that Date object will hold.

No Parameter

If no parameter is given, the Date object will be set to the current date and time.

const d = new Date()

A Timestamp

An integer representing the number of milliseconds since January 1, 1970 00:00:00 UTC can be given.

const d = new Date(1500000000000)

A Date String

A string value representing a date and in a format recognized by the Date.parse()open in new window method can be given. The standard date-time string format is as follows:

NOTE

Setting dates using a date string is discouraged due to potential inconsistencies.

const d = new Date('July 13, 2017 22:40')

Individual Date Components

Each part of a date (year, month, day, hour, minute, second, and millisecond) can be given as a separate parameter. Only the year and month are required and any missing fields will be given the lowest possible value.

When working with Date components, it is important to remember that the month values begins with 0 for January and ends with 11 for December.

const d = new Date(2017, 6, 13, 22, 40)

Instance Methods

Date instance methods can be used to get, set, or display dates. The following methods are some of the more commonly used.

Getting Date Elements

It is possible to get any part of a Date instance using methods.

methodreturns
getDate()open in new windowReturns the day of the month as a number between 1 and 31.
getDay()open in new windowReturns the day of the week as a number between 0 and 6.
getFullYear()open in new windowReturns the year as a 4-digit number.
getHours()open in new windowReturns the hour as a number between 0 and 23.
getMinutes()open in new windowReturns the minutes as a number between 0 and 59.
getMonth()open in new windowReturns the month as a number between 0 and 11.
getTime()open in new windowReturns the number of milliseconds since Unix Epoch.

Setting Date Elements

It is possible to set any part of the Date instance using methods. The following methods are some of the more commonly used.

methodparametersreturns
setDate()open in new windowA number representing the day of the monthSets the day of a Date instance relative to the beginning of the currently set month. If the day provided is outside of the month range, the method will update the month and year accordingly.
setFullYear()open in new windowA number with the numeric value of the desired year. Optionally, a month and date can also be set.Sets the full year of a Date instance.
setHours()open in new windowA number representing the hour. Optionally, the minutes and seconds can also be set.Sets the hour of a Date instance.
setMonth()open in new windowA number representing the month of the year, where 0 represents January and 11 represents December. Optionally, a day can be set.Sets the month for of Date instance.

Displaying Dates

Date methods can be used to display dates in different formats. The following methods are some of the more commonly used.

methodreturnsexample
toDateString()open in new windowReturns the date portion of the a Date instance.Thu Jul 13 2017
toLocaleDateString()open in new windowReturns the date portion of the Date instance in a format that matches the set locale. The locale can be explicitly set and options can be used to manipulate how the date string will appear.7/13/2017
toLocaleString()open in new windowReturns the Date instance in a format that matches the set locale. The locale can be explicitly set and options can be used to manipulate how the date string will appear.7/13/2017, 10:40:00 PM

Calculating Difference

Calculating the difference between dates, either time passed or a count down to, is a common use of the dates in JavaScript. The following are examples of how to do those calculations.

Comparing Dates

Because all dates in JavaScript are essentially based on the number of milliseconds since the Unix Epoch, it can be one of the easiest ways to compare dates. The getTime() method can be used to get the number of milliseconds for a specific Date instance.

const canadaDay = new Date('July 1, 2020')
const newYear = new Date('January 1, 2021')

canadaDay.getTime() // 1593576000000
newYear.getTime()   // 1609477200000

As we can see from the example above the later a date is, the larger the number returned from the getTime() method. Because getTime() returns a number, standard compares can be used.

const canadaDay = new Date('July 1, 2020')
const now = new Date()

if (now.getTime() < canadaDay.getTime()) {
  document.write("Still waiting for Canada Day.")
} else {
  document.write("Canada Day has passed.")
}

Of course, sometimes we are looking for a specific date, and we need to know two dates match. This can be accomplished by comparing the different components of the two Date instances.

const canadaDay = new Date('July 1, 2020')
const independenceDay = new Date('July 4, 2020')

canadaDay.getMonth() === independenceDay.getMonth() // true
canadaDay.getDate() === independenceDay.getDate() // false

Countdown

Creating a countdown or an elapsed time, simply involves subtracting one date by another using the getTime(). You may wish to convert the milliseconds to a larger unit like hours or days.

NOTE

There are 1000 milliseconds in a second and 60 seconds in a minute. There are 60 minutes in an hour and 24 hours in a day. Finally, there are 365.25 days in a year.

const canadaDay = new Date('July 1, 2020')
const now = new Date()

// convert milliseconds to days
// since we want whole days Math.floor is used to drop extra time
function msToDays (date) {
  return Math.floor(date.getTime() / 1000 / 60 / 60 / 24)
}

// Calculating difference
const difference = msToDays(canadaDay) - msToDays(now)

if (difference > 0) {
  // Canada Day has yet to come
} else if (difference < 0) {
  // Canada Day has passed
} else {
  // It is Canada Day
}

See Also

References