Understanding the Date Object
The Date object can be created using the following syntax:
var today = new Date();
The above code creates a new Date object representing the current date and time. The
Date() constructor can also be passed a string representation of a date, and it will parse the string and create a new Date object based on that string.
Displaying the Current Date
var today = new Date(); document.write("Today's date is " + today);
Is code uses the built-in
document.write method is then used to write the string “Today’s date is” along with the value of the
today variable to the web page.
Customizing the Date Format
var today = new Date(); var date = (today.getMonth()+1) + "-" + today.getDate() + "-" + today.getFullYear(); document.write("Today's date is " + date);
In this example, the
getMonth() method is used to retrieve the current month, with the result incremented by one to account for the zero-based indexing of the
Date object. The
getDate() method is then used to retrieve the current day of the month, and the
getFullYear() method is used to retrieve the current year. Finally, these values are combined into a string that is written to the web page using the
Thanks for reading. Happy coding!