Follow @endyourif rss Facebook LinkedIn

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

Published on Feb 7, 2018

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.


Tags: Javascript | JavaScript | slice

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP