How do I retrieve the month from the current date in mm format? (i.e. "05")
This is my current code:
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
if (currentMonth < 10) { currentMonth = '0' + currentMonth; }
if(currentMonth < 9) { currentMonth = "0" + currentMonth; } and it did not work. Guess I need single quotes instead of double.+ operator ..< 10 else 9 wont return '09'toString in an else.toString in the else, so that 10, 11, and 12 (can't believe i missed october in my last comment) are also strings, even though they don't have a leading 0. Gert G's solution is another way of achieving the same effect.If you do this
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
then currentMonth is a number, which you can format as you want, see this question that will help you with formatting: How can I format an integer to a specific length in javascript?
In order for the accepted answer to return a string consistently, it should be:
if(currentMonth < 10) {
currentMonth = '0' + currentMonth;
} else {
currentMonth = '' + currentMonth;
}
Or:
currentMonth = (currentMonth < 10 ? '0' : '') + currentMonth;
Just for funsies, here's a version without a conditional:
currentMonth = ('0' + currentMonth).slice(-2);
Edit: switched to slice, per Gert G's answer, credit where credit is due; substr works too, I didn't realize it accepts a negative start argument
An alternative with ES6 template strings
A solution for mm/yyyy. Not quite the question, but I guess remove the second part.
const MonthYear = `${dateObj.getMonth() < 10 ? '0' : '' }${dateObj.getMonth()+1}/${dateObj.getFullYear()}`
const Month = `${dateObj.getMonth() < 10 ? '0' : '' }${dateObj.getMonth()+1}`
An answer here referenced one on number formatting but without a code example. This is a general string padding problem that has been simplified since ES2017. You can use String.prototype.padStart and String.prototype.padEnd to make sure that a string is of a fixed minimum length.
The return of Date.prototype.getMonth is a number from 0 (January) to 11 (December). To be represented as strings from '01' to '12' you might do:
let date = new Date()
let month = date.getMonth() + 1
let display = month.toString().padStart(2, '0')
console.log(display) // one of "01", "02", ..., "09", "10", "11", "12"
This similarly applies to the return of Date.prototype.getDate, a number from 1 to 31:
console.log(
new Date().getDate().toString().padStart(2, '0')
) // one of "01", "02", ..., "31"
Or simply any value that you want to be a string with a minimum length:
let greeting = 'world'.padStart(17, 'hello ')
console.log(greeting) // "hello hello world"