Home  >  Article  >  Web Front-end  >  How to Append the Current Date in dd/mm/yyyy Format to an Input Using Javascript?

How to Append the Current Date in dd/mm/yyyy Format to an Input Using Javascript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 19:48:29347browse

How to Append the Current Date in dd/mm/yyyy Format to an Input Using Javascript?

How to Get and Format Current Date in Javascript Appending It to Input

To add a current date in dd/mm/yyyy format to a hidden HTML input field, you can utilize Javascript. Follow these steps:

  1. Create a new Date object: Instantiate a Date object (const today = new Date();) to represent the current date.
  2. Extract Date Components: Extract the year (yyyy), month (mm), and day (dd) from the Date object.
  3. Format the Date: Add leading zeros to ensure proper formatting, especially for single-digit months and days.
  4. Construct the Formatted Date: Concatenate the formatted components (dd '/' mm '/' yyyy) to obtain the desired dd/mm/yyyy format.
  5. Update HTML Input: Set the value attribute of the hidden input element (document.getElementById('DATE').value = formattedToday;) to the formatted current date.

Example Code:

<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>

The above is the detailed content of How to Append the Current Date in dd/mm/yyyy Format to an Input Using Javascript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn