JavaScript Date object
The JavaScript Date object can be used to retrieve the year, month, and day, and it can also be utilized to display a timer on a webpage.
You can create a Date object using various constructors, and it provides methods to get and set the day, month, year, hour, minute, and seconds.
Constructor
You can use four different variants of the Date constructor to create a Date
object.
1. Data()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month , day, hours, minutes,
seconds, milliseconds)
JavaScript Methods
Here is a list of JavaScript Date methods along with their descriptions.
JavaScript Date Example
Here’s a simple example to print a Date object, which displays both the date
and time.
<Script>
let currentDate = new Date();
console.log(currentDate);
</Script>
Here is another example of printing the date, month, and year from a Date
object in JavaScript:
<Script>
let currentDate = new Date();
let day = currentDate.getDate();
let month = currentDate.getMonth() + 1;
// getMonth() returns 0-11, so add 1
let year = currentDate.getFullYear();
console.log("Date: " + day);
console.log("Month: " + month);
console.log("Year: " + year);
</Script>
When you run this code, it will print the current date, month, and year
separately:
JavaScript Current Time Example
Here’s a simple example to print the current system time.
<Script>
let currentTime = new Date();
let hours = currentTime.getHours();
let minutes = currentTime.getMinutes();
let seconds = currentTime.getSeconds();
console.log("Current Time: " + hours + ":" + minutes + ":" + seconds);
</Script>
When you run this code, it will print the current time in the format
`HH:MM:SS`:
JavaScript digital clock Example
Here’s a simple example of displaying a digital clock using the JavaScript
Date object.
In JavaScript, you can set intervals in two ways: using the setTimeout()
method or the setInterval() method.
<Script>
function updateClock() {
let currentTime = new Date();
let hours = currentTime.getHours();
let minutes = currentTime.getMinutes();
let seconds = currentTime.getSeconds();
// Format the time as HH:MM:SS
let formattedTime =
`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2,
'0')}:${seconds.toString().padStart(2, '0')}`;
// Display the time on the page
document.getElementById('clock').innerText = formattedTime;
}
// Update the clock every second
setInterval(updateClock, 1000);
// Initialize the clock
updateClock();
</Script>
HTML:
<div id="clock">00:00:00</div>
Note: The output will change every second
to reflect the current time.