Home >Web Front-end >JS Tutorial >How Can I Get and Format the Current Date in JavaScript?
In JavaScript, you can retrieve the current date and time using the new Date() constructor. This constructor creates a new Date object initialized with the current date and time.
To format the current date as a string, you can use the following steps:
The following JavaScript code demonstrates how to get the current date as a formatted string:
var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0! var yyyy = today.getFullYear(); today = mm + '/' + dd + '/' + yyyy; document.write(today);
This code will output the current date in the following format: mm/dd/yyyy. For example, if the current date is March 8, 2023, the output would be "03/08/2023".
The above is the detailed content of How Can I Get and Format the Current Date in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!