Javascript add leading zero to day and month

If you code in JavaScript, you will notice that the display of dates and times in this programming language is not standard. Numbers are displayed as integers, not characters. But how to display zeros in front of the numbers down 10?
We will answer this question by a simple example.


If you are using JavaScript to manipulate the dates, you might face a problem showing them, because the final result will look like this:

e.g. January 09, 2016: 2016-1-9

To handle this, you need to add leading zero to day and month if needed.
The following code will do it automatically for you.

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

Final result: 2016-01-09

Print Friendly, PDF & Email

Comments are closed.