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

How to Retrieve and Format the Current Date (dd/mm/yyyy) in JavaScript?

Barbara Streisand
Release: 2024-10-21 19:44:29
Original
450 people have browsed it

How to Retrieve and Format the Current Date (dd/mm/yyyy) in JavaScript?

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

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!

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!