Just want to covert Jan to 01 (date format)
I can use array()
but looking for another way...
Any suggestion?
Just for fun I did this:
function getMonthFromString(mon){
return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}
Bonus: it also supports full month names :-D Or the new improved version that simply returns -1 - change it to throw the exception if you want (instead of returning -1):
function getMonthFromString(mon){
var d = Date.parse(mon + "1, 2012");
if(!isNaN(d)){
return new Date(d).getMonth() + 1;
}
return -1;
}
Sry for all the edits - getting ahead of myself
If you are using moment.js:
moment().month("Jan").format("M");
Here is a modified version of the chosen answer:
getMonth("Feb")
function getMonth(month) {
d = new Date().toString().split(" ")
d[1] = month
d = new Date(d.join(' ')).getMonth()+1
if(!isNaN(d)) {
return d
}
return -1;
}
If you don't want an array then how about an object?
var months = {
'Jan' : '01',
'Feb' : '02',
'Mar' : '03',
'Apr' : '04',
'May' : '05',
'Jun' : '06',
'Jul' : '07',
'Aug' : '08',
'Sep' : '09',
'Oct' : '10',
'Nov' : '11',
'Dec' : '12'
}
One more way to do the same
month1 = month1.toLowerCase();
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
month1 = months.indexOf(month1);