Zero Padding a Number with JavaScript

Published on Feb 7, 2018 by Jamie Munro

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.

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!

Tags: Javascript | JavaScript | slice

Related Posts

blog comments powered by Disqus