JavaScript Date Object
This YouTube video was created by Steve Griffith.
The JavaScript Date
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()
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()
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.
method | returns |
---|---|
getDate() | Returns the day of the month as a number between 1 and 31. |
getDay() | Returns the day of the week as a number between 0 and 6. |
getFullYear() | Returns the year as a 4-digit number. |
getHours() | Returns the hour as a number between 0 and 23. |
getMinutes() | Returns the minutes as a number between 0 and 59. |
getMonth() | Returns the month as a number between 0 and 11. |
getTime() | Returns 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.
method | parameters | returns |
---|---|---|
setDate() | A number representing the day of the month | Sets 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() | A 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() | A number representing the hour. Optionally, the minutes and seconds can also be set. | Sets the hour of a Date instance. |
setMonth() | A 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.
method | returns | example |
---|---|---|
toDateString() | Returns the date portion of the a Date instance. | Thu Jul 13 2017 |
toLocaleDateString() | Returns 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() | Returns 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
- Timestamps, Date.now() and valueOf() | YouTube
- International Date & Time Formatting with JavaScript | YouTube
- A Complete Tutorial on the new MomentJS Library - Luxon JS | YouTube