How to Get Two Digits Month and Date Value in Javascript

How to Get Two Digits Month and Date Value in Javascript

By default, Javascript getMonth() and getDate() methods don’t return two digits format (i.e, 0 preceding with single-digit value) for month and date. We can overcome that limitation by creating a function with just one line.

Two Digits Date Format in JS

function getTwoDigitDateFormat(monthOrDate) {
  return (monthOrDate < 10) ? '0' + monthOrDate : '' + monthOrDate;

var date = new Date();

var twoDigitDate = getTwoDigitDateFormat(date.getDate());
console.log("Two Digit Date: " + twoDigitDate); // example output: Two Digit Date: 02

var twoDigitMonth = getTwoDigitDateFormat(date.getMonth() + 1);
console.log("Two Digit Month: " + twoDigitMonth); // example output: Two Digit Month: 09

By creating this simple Javascript function, you can precede the single-digit month and date with ‘0’.  The getTwoDigitDateFormat function has one parameter called monthOrDate which may either be a month or a date.

Inside the getTwoDigitDateFormat function, I am checking whether the value of month/date is lesser than 0 or not. If it’s lesser than 0, then the function will return the month/date with ‘0’ preceding its value.

Otherwise, it will simply return the month/date value. I invoked the getTwoDigitDateFormat functions two times with different argument, date.getDate() to get the current date and date.getMonth() to get the current month.

Increase the getMonth() Value

var twoDigitMonth = getTwoDigitDateFormat(date.getMonth() + 1);

You might wonder what I had done by adding 1 when passing the getMonth() parameter in the function. By default, Javascript getMonth() method starts with 0 as arrays do in most of the popular programming languages. In other words, The numeric equivalent of January is 0 not 1 (which is February) in Javascript. By increasing the value by 1 we can get rid of this problem.

Hope it helps, if you have any other methods to solve this problem let me know by making a comment below. Thank you