Constructors: Date()

What is the purpose of the Date() constructor?

The Date() constructor is used to create Date objects in JavaScript, which represent points in time. Date objects allow you to work with dates and times, including getting the current date and time, manipulating dates, and formatting date and time values.

Example of Using the Date() Constructor

            
// Create a new Date object for the current date and time
const now = new Date()
console.log('Current Date and Time:', now)
            
        

Common Methods of Date Objects

Practical Use Case

You can use the Date() constructor to display the current year in a website footer, calculate the difference between two dates, or format dates for display.

            
// Display the current year in the footer
const currentYear = new Date().getFullYear()
document.getElementById('footer').innerText = `© ${currentYear} My Website
            
        

References:

Library of Date and Time

For more advanced date and time manipulation, consider using libraries like Moment.js, luxon, or date-fns.

Open the console to see the output