How do I get Month and Date of JavaScript in 2 digit format?
Solution 1:
("0" + this.getDate()).slice(-2)
for the date, and similar:
("0" + (this.getMonth() + 1)).slice(-2)
for the month.
Solution 2:
If you want a format like "YYYY-MM-DDTHH:mm:ss", then this might be quicker:
var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ
Or the commonly used MySQL datetime format "YYYY-MM-DD HH:mm:ss":
var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
I hope this helps
Solution 3:
Why not use padStart
?
padStart(targetLength, padString)
where
-
targetLength
is2
-
padString
is0
// Source: https://stackoverflow.com/a/50769505/2965993
var dt = new Date();
year = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day = dt.getDate().toString().padStart(2, "0");
console.log(year + '/' + month + '/' + day);
This will always return 2 digit numbers even if the month or day is less than 10.
Notes:
- This will only work with Internet Explorer if the js code is transpiled using babel.
-
getFullYear()
returns the 4 digit year and doesn't requirepadStart
. -
getMonth()
returns the month from 0 to 11.- 1 is added to the month before padding to keep it 1 to 12.
-
getDate()
returns the day from 1 to 31.- The 7th day will return
07
and so we do not need to add 1 before padding the string.
- The 7th day will return
Solution 4:
Example for month:
function getMonth(date) {
var month = date.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
You can also extend Date
object with such function:
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}