Home >Web Front-end >JS Tutorial >How to Add a Formatted Date to an Input Field Using JavaScript?

How to Add a Formatted Date to an Input Field Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-21 19:42:02521browse

How to Add a Formatted Date to an Input Field Using JavaScript?

How to Add a Formatted Date to an Input Field in JavaScript

You want to attach the current date to a hidden HTML field for server transmission:

<code class="html"><input type="hidden" id="DATE" name="DATE" value="WOULD_LIKE_TO_ADD_DATE_HERE"></code>

Solution:

Utilize the following JavaScript code:

<code class="js">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>

Additional Information:

  • Getting the Current Date: Use the new Date() constructor.
  • Formatting the Date: Pad single-digit dates with zeros using conditional statements.

The above is the detailed content of How to Add a Formatted Date to an Input Field 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