The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get and set day, month, year, hour, minute and seconds.
You can use 4 variant of Date constructor to create date object.
The important methods of date object are as follows:
Method | Description |
---|---|
getFullYear() | returns the year in 4 digit e.g. 2015. It is a new method and suggested than getYear() which is now deprecated. |
getMonth() | returns the month in 2 digit from 0 to 11. So it is better to use getMonth()+1 in your code. |
getDate() | returns the date in 1 or 2 digit from 1 to 31. |
getDay() | returns the day of week in 1 digit from 0 to 6. |
getHours() | returns all the elements having the given name value. |
getMinutes() | returns all the elements having the given class name. |
getSeconds() | returns all the elements having the given class name. |
getMilliseconds() | returns all the elements having the given tag name. |
Let's see the simple example to print date object. It prints date and time both.
See this example:
Output:
Let's see another code to print date/month/year.
Let's see the simple example to print current time of system.
See this example:
Output:
Let's see the simple example to display digital clock using JavaScript date object.
There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.
See this example:
Output: