JavaScript Date
Heading h1
JavaScript Date is used to work with dates and times in JavaScript.
Syntax
The syntax for creating a new Date object is:
var d = new Date();
Example
Here is an example of creating a new Date object:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Function Example</title>
</head>
<body>
<!-- Placeholder for displaying the output -->
<p id="output"></p>
<script>
// Create a new Date object representing the current date and time
var currentDate = new Date();
// Display the current date and time
document.getElementById("output").innerHTML += "Current Date and Time: " + currentDate + "<br>";
// Get specific components of the date
var year = currentDate.getFullYear();
var month = currentDate.getMonth() + 1; // Months are zero-based, so add 1
var day = currentDate.getDate();
var hours = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
// Display specific components of the date
document.getElementById("output").innerHTML += "Year: " + year + "<br>";
document.getElementById("output").innerHTML += "Month: " + month + "<br>";
document.getElementById("output").innerHTML += "Day: " + day + "<br>";
document.getElementById("output").innerHTML += "Time: " + hours + ":" + minutes + ":" + seconds;
</script>
</body>
</html>
Output
The output of the above example will be the current date and time in the user's timezone.
Current Date and Time: Sun Nov 19 2023 16:57:22 GMT+0530 (India Standard Time)
Year: 2023
Month: 11
Day: 19
Time: 16:57:22