Zero Padding a Number with JavaScript

Z

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:

[code]
var today = new Date();
var formattedDate = today.getFullYear() +
(‘0’ + parseInt(today.getMonth() + 1)).slice(-2) +
(‘0’ + today.getDate()).slice(-2);
[/code]

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!

About the author

By Jamie

My Books