Zero Padding a Number with JavaScript Zero Padding a Number with JavaScript

This morning I had to format a date using JavaScript as follows: yyyymmdd requiring both the month and day to include a leading zero when the month or day was less than 10. This solution using slice multiple times.


Zero Padding a Javascript Date

A nice solution I found was as follows:


var today = new Date();
var formattedDate = today.getFullYear() +
('0' + parseInt(today.getMonth() + 1)).slice(-2) +
('0' + today.getDate()).slice(-2);

The solution is to create a string with the number of leading zeros you require. In the example above, I need only one leading zero. So I concatenated a 0 with today's month, then sliced the last two characters: .slice(-2). If the month was greater than 9, the last two characters would be the entire month. However, when it is less than 10, it would include the leading zero I concatenated.

This could easily accomplish more zero padding by updating the string to include more zeros and changing the slice value to the length of your string.

Enjoy!

Published on Feb 7, 2018

Tags: Javascript | JavaScript | slice

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.