Home > Web Front-end > JS Tutorial > How to Add Leading Zeroes to Dates in JavaScript?

How to Add Leading Zeroes to Dates in JavaScript?

Linda Hamilton
Release: 2024-12-11 13:30:24
Original
305 people have browsed it

How to Add Leading Zeroes to Dates in JavaScript?

Adding Leading Zeroes to Dates in JavaScript

To calculate the date for 10 days in advance in the format of dd/mm/yyyy, you can use the following script:

var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate() + 10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
Copy after login

However, to ensure the day and month component appear with leading zeroes, the script needs to incorporate the following rules:

if (MyDate.getMonth() < 10) getMonth = '0' + getMonth;
if (MyDate.getDate() < 10) get.Ddate = '0' + getDate;
Copy after login

Here's an example of how to implement these rules:

var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() + 20);

MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
             + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
             + MyDate.getFullYear();
Copy after login

The .slice(-2) method extracts the last two characters of the string, ensuring that the day and month component always appear with leading zeroes.

The above is the detailed content of How to Add Leading Zeroes to Dates in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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