Skip to content

JavaScript: date with leading zeros

18 November 2016

Seeing lot of questions (and answers) to this problem here is another posible solutions using regex, which I didn’t find so far.

First a set up

We need a date as a string, so let’s create one, define a separator and transform it into a string as a short date format.

var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());

So far the result will be

2016.6.1

We’d like to add zeros and transform it into

2016.06.01

To do this we apply a regex

/\b\d{1}\b/

stating that we’re looking for single figure into a boundary (dots in the case)
if something is found we concatenate a leading zero to it.
So here it is:

strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")
alert(strDate + '; reversed: '+ strDate.split(separator).reverse().join(separator));

Test it here or try it yourself!

Leave a Comment

Leave a comment