DenisKarakchiev
9/7/2017 - 7:54 AM

zero leading in date #js

zero leading in date #js

var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() + 20);

MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
             + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
             + MyDate.getFullYear();

EDIT:

To explain, .slice(-2) gives us the last two characters of the string.

So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.

So if the MyDate.getMonth() returns 9, it will be:

("0" + "9") // Giving us "09" so adding .slice(-2) on that gives us the last two characters which is:

("0" + "9").slice(-2) "09" But if MyDate.getMonth() returns 10, it will be:

("0" + "10") // Giving us "010" so adding .slice(-2) gives us the last two characters, or:

("0" + "10").slice(-2) "10"