The JavaScript Date object provides a way to work with dates and times in JavaScript. You can create Date objects to represent a specific date and time.
With the Date object, you can perform operations like getting the current date and time, converting between different date formats, and calculating the difference between two dates.
Here are some Date objects’ built-in methods that perform various operations on dates and times.
- new Date() – This method creates a new Date object with the current date and time.
- Date.parse() – This method converts a date string into a timestamp (the number of milliseconds since January 1, 1970, 00:00:00 UTC).
- Date.UTC() – This method returns the number of milliseconds between January 1, 1970, 00:00:00 UTC, and a specified date and time.
- getDate() – This method returns the day of the month (from 1 to 31) for a specified Date object.
- getMonth() – This method returns the month (from 0 to 11) for a specified Date object.
- getFullYear() – This method returns the year (four digits for dates between 1000 and 9999) for a specified Date object.
- getHours() – This method returns the hour (0 to 23) for a specified Date object.
- getMinutes() – This method returns the minutes (0 to 59) for a specified Date object.
- getSeconds() – This method returns the seconds (0 to 59) for a specified Date object.
- getTime() – This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC for a specified Date object.
JavaScript Date Object examples
A simple example code shows how to create a Date object and use some of its methods to display the current date and time:
<!DOCTYPE html>
<html>
<body>
<script>
// Create a new Date object
const currentDate = new Date();
// Get the current date and time components
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1;
const day = currentDate.getDate();
const hours = currentDate.getHours();
const minutes = currentDate.getMinutes();
const seconds = currentDate.getSeconds();
// Display the current date and time
console.log(`The current date is: ${month}/${day}/${year}`);
console.log(`The current time is: ${hours}:${minutes}:${seconds}`);
</script>
</body>
</html>
Output:
Comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version