Getting Current Formatted Date (dd/mm/yyyy) in JavaScript
When appending a hidden HTML field with the current date, such as:
,
a formatted date can be assigned to the VALUE attribute using JavaScript code. Here's how you can do it:
<code class="javascript">const today = new Date(); const yyyy = today.getFullYear(); let mm = today.getMonth() + 1; // Months start at 0! let dd = today.getDate(); if (dd < 10) dd = '0' + dd; if (mm < 10) mm = '0' + mm; const formattedToday = dd + '/' + mm + '/' + yyyy; document.getElementById('DATE').value = formattedToday;</code>
This code snippet first initializes today as a new Date object, and then retrieves the year (yyyy), month (mm), and day (dd) values from it. Leading zeros are added to ensure a consistent dd/mm/yyyy format.
Finally, the formattedToday variable is assigned to the value attribute of the DATE input field, now containing the current date in the desired format.
The above is the detailed content of How to Retrieve and Format the Current Date (dd/mm/yyyy) in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!