Once the date object is created, you can apply different operations to it. You can show a timer on your website using the date object.
Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:
- Use the F12 key in Chrome and other chromium-based browsers.
- Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
- Use Option + ⌘ + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing ⌘ +, and in Advanced tab check “Show Develop menu in menu bar”).
The new Date() function without any parenthesis creates an object with the current date. We can also pass arguments to the new Date() function to create new date objects with any specified date and time. The arguments use the following syntax in the new Date() function:
We can pass (minimum) 1 to (maximum) 7 arguments to the new Date() function.
Now let’s try with five parameters:
The seconds are 00 by default.
In the same way, we can also give two, three, four, and six arguments. The order of the arguments will always remain the same unless we are only giving a single argument.
If only one parameter is supplied to the new Date() function, it will be considered as milliseconds:
The time shown in the screenshot above is 2001 milliseconds past midnight of January 01, 1970.
One or two-digit years will be considered from the previous century:
We can also pass a date string to the new Date() function:
The getFullYear() method:
The getFullYear() method can be used to get the year from the date object.
The getMonth() method:
The getMonth() method returns the value of the month in the date object.
Note: This value is always one less than the actual month.
Similarly the getDate(), getHours(), getMinutes(), getSeconds() and getMilliseconds() can be used to get the individual values of Date, Hours, Minutes, Seconds and Milliseconds respectively.
The getTime() method:
The getTime method can be used to get the number of milliseconds that have passed since midnight Jan 1, 1970:
The getDay() method:
The setFullYear() method:
The setFullYear() method is used to set the year of the date object. It can optionally set the month and the day of the date object as well.
The setMonth() method:
The setMonth() method is used to set the month in the date object.
Similarly the setDate(), setHours(), setMinutes(), setSeconds() and setMilliseconds() can be used to set the individual values of Date, Hours, Minutes, Seconds and Milliseconds (respectively) in the date object.
The setTime() method:
The setTime method can be used to set time in milliseconds after midnight of Jan 01, 1970.
In this post, we discussed what a date object is and how to create it. Moreover, we also learned some methods which we can use to operate on a date object and manipulate it according to our needs.