Just want to covert Jan to 01 (date format)
I can use array()
but looking for another way...
Any suggestion?
This question is related to
javascript
date
I usually used to make a function:
function getMonth(monthStr){
return new Date(monthStr+'-1-01').getMonth()+1
}
And call it like :
getMonth('Jan');
getMonth('Feb');
getMonth('Dec');
If you are using moment.js:
moment().month("Jan").format("M");
function getMonthDays(MonthYear) {
var months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
var Value=MonthYear.split(" ");
var month = (months.indexOf(Value[0]) + 1);
return new Date(Value[1], month, 0).getDate();
}
console.log(getMonthDays("March 2011"));
Here is a simple one liner function
//ECHMA5
function GetMonth(anyDate) {
return 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];
}
//
// ECMA6
var GetMonth = (anyDate) => 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];
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;
}
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);
Another way;
alert( "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf("Jun") / 3 + 1 );
Here is another way :
var currentMonth = 1
var months = ["ENE", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AGO", "SEP", "OCT", "NOV", "DIC"];
console.log(months[currentMonth - 1]);
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
then just call monthNames[1] that will be Feb
So you can always make something like
monthNumber = "5";
jQuery('#element').text(monthNames[monthNumber])
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'
}
Source: Stackoverflow.com