Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-21 19:48:29
Original
346 people have browsed it

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!