In this tutorial we will learn how to use of date object in JavaScript. JavaScript provides built-in support for working with dates and times through the Date object.
To create a Date object, you can use the new keyword followed by the Date() constructor.
The new Date() Syntax
const now = new Date();
document.write(now);
This will output the current date and time in your browser's console.
You can also pass arguments to the Date() constructor to create a Date object for a specific date and time. The arguments are the year, month (0-based), day, hour, minute, second, and millisecond.
The new Date(year, month (0-based), day, hour, minute, second, and millisecond) Syntax:
const date = new Date(2022, 6, 26, 12, 30, 0, 0);
document.write(date);
This will output a Date object representing June 26, 2022, at 12:30:00 PM.
You can also format dates and times using the toLocaleString() method, which returns a string representing the date and time in a localized format.
Example
const now = new Date();
const localizedDate = now.toLocaleString(); // returns a string representing the current date and time in a localized format
document.write(localizedDate);
This will output a string representing the current date and time in a localized format, like "6/26/2023, 12:30:00 PM" depending on your browser's language and settings.
Once you have a Date object, you can use its methods to get and set various date and time components, like the year, month, day, hour, minute, second, and millisecond.
Here are some examples of date and time.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>TutorialsTrend - JavaScript Date and Time Examples</h2>
<script>
const now = new Date();
document.write("Date - " + now + "</br>") // return the current date and time
const year = now.getFullYear();
document.write("getFullYear - " + year + "</br>") // returns the current year
const month = now.getMonth();
document.write("getMonth - " + month + "</br>") // returns the current Month
const day = now.getDate();
document.write("getDate - " + day + "</br>") // return the day of the month
const hours = now.getHours();
document.write("getHours - " + hours + "</br>") // return the number of hours into the day
const minutes = now.getMinutes();
document.write("getMinutes - " + minutes + "</br>") // return the number of minutes into the hour
const seconds = now.getSeconds();
document.write("getSeconds - " + seconds + "</br>") // return the number of Seconds into the minute
const milliseconds = now.getMilliseconds();
document.write("getMilliseconds - " + milliseconds + "</br>") // return the number of Seconds into the second
</script>
</body>
</html>
Output