Easiest way to convert month name to month number in JS ? (Jan = 01)

JavascriptDate

Javascript Problem Overview


Just want to covert Jan to 01 (date format)

I can use array() but looking for another way...

Any suggestion?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Another way;

alert( "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf("Jun") / 3 + 1 );

Solution 3 - Javascript

If you don't want an array then how about an object?

const 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',
}

Solution 4 - Javascript

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);

Solution 5 - Javascript

If you are using moment.js:

moment().month("Jan").format("M");

Solution 6 - Javascript

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');

Solution 7 - Javascript

For anyone still looking at this answer in 2021, toLocaleDateString now has broad support

let monthNumberFromString = (str) => {
  return new Date(`${str} 01 2000`).toLocaleDateString(`en`, {month:`2-digit`})
}
// monthNumberFromString(`jan`) returns 01

Solution 8 - Javascript

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"));

Solution 9 - Javascript

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])

Solution 10 - Javascript

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;
}

Solution 11 - Javascript

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]);

Solution 12 - Javascript

function getNumericMonth(monthAbbr) {
      return (String(['January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'].indexOf(monthAbbr) + 1).padStart(2, '0'))
    }
    
   console.log(getNumericMonth('September'));

Solution 13 - Javascript

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()];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionl2aelbaView Question on Stackoverflow
Solution 1 - JavascriptAaron RomineView Answer on Stackoverflow
Solution 2 - JavascriptAlex K.View Answer on Stackoverflow
Solution 3 - JavascriptPaul S.View Answer on Stackoverflow
Solution 4 - JavascriptVikas HardiaView Answer on Stackoverflow
Solution 5 - JavascriptchinupsonView Answer on Stackoverflow
Solution 6 - JavascriptAkhil SekharanView Answer on Stackoverflow
Solution 7 - JavascriptqbuntView Answer on Stackoverflow
Solution 8 - JavascriptMuzafar HasanView Answer on Stackoverflow
Solution 9 - JavascriptArturo Romero MarquezView Answer on Stackoverflow
Solution 10 - JavascriptChris MartinView Answer on Stackoverflow
Solution 11 - JavascriptErick GarciaView Answer on Stackoverflow
Solution 12 - JavascriptRAKESH CHOUDHARYView Answer on Stackoverflow
Solution 13 - JavascriptLiran BarnivView Answer on Stackoverflow