views:

85

answers:

4

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;
+1  A: 
if (currentMonth < 10) { currentMonth = '0' + currentMonth; }
Matt
Thanks! I originally had `if(currentMonth < 9) { currentMonth = "0" + currentMonth; }` and it did not work. Guess I need single quotes instead of double.
Michael Kniskern
Odd.. the type of quote shouldn't matter! Maybe an artifact of type coercion and the `+` operator ..
Matt
You want `< 10` else 9 wont return '09'
Alex K.
@Alex K. - thanks, quite right. cocaine's a hell of a drug.
Matt
@Matt: a minor thing, sure, but now you have an int if it's november or december, and a string in all other cases. this could lead to some unexpected behavior upon further concatenation (if the other concatenated value is numeric, say). i'd `toString` in an `else`.
David Hedlund
@David Hedlund - I would agree, but it's not possible to have a leading 0 without it being a string.
Matt
@Matt: yes, that's why I'm suggesting that you do `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.
David Hedlund
+2  A: 

An alternative way:

var currentMonth=('0'+(currentDate.getMonth()+1)).slice(-2)
Gert G
+1 because I copied you for part of my answer.
eyelidlessness
+1 for elegance
David Hedlund
Thanks guys! :)
Gert G
A: 

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

eyelidlessness
A: 

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: http://stackoverflow.com/questions/1127905/how-can-i-format-an-integer-to-a-specific-length-in-javascript

Igor Pavelek