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
Release: 2024-10-21 19:42:02
Original
530 people have browsed it

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

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

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!

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