57

Just want to covert Jan to 01 (date format)

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

Any suggestion?

MartyIX
  • 27,828
  • 29
  • 136
  • 207
l2aelba
  • 21,591
  • 22
  • 102
  • 138

13 Answers13

102

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

Aaron Romine
  • 1,539
  • 1
  • 9
  • 8
  • Well - keep in mind: I haven't tested it - this was off the cuff. You might want to try/catch and handle the NaN condition (if the date format was incorrect). I might update with that. – Aaron Romine Nov 26 '12 at 14:21
  • 1
    @l2aelba Congrats on picking the slowest solution. http://jsperf.com/month-number-speed-test – epascarello Nov 26 '12 at 14:35
  • 1
    @epascarello I'll agree it's slow - just answering OP's question with what he wanted. Efficiency isn't that big of deal: would I use this when I parse 300+ strings? Absolutely not! But if all he's doing is a few runs on each page, then I don't think it matters. – Aaron Romine Nov 26 '12 at 14:39
  • 5
    +1 This may be the slowest, but it's also the only answer on this page that's case-insensitive, locale-safe, has obvious intent, and has a decent failure mode on bad input. – Ian McLaird Feb 24 '15 at 15:30
  • Yes, all the other answers ignore case and local. – Pop-A-Stash Sep 09 '15 at 17:16
  • What's with the +1 in returning the getMonth value? Seems to throw off date creation by one every time. – BadPirate Jan 03 '17 at 19:47
  • Ha, I finally read this. getMonth returns a zero index month number (i.e. Jan = 0, Feb = 1). If it's being thrown off, it's possible you have an override of the getMonth method on the prototype of Date that returns the 'right' month number which would cause a one off. – Aaron Romine Apr 11 '17 at 17:20
  • correct me if I am wrong but it seems that a comma is missing : `var d = Date.parse(mon +",1, 2012");` – stucash Jan 29 '21 at 16:42
  • Check the facts. `t = Date.now(); for (i=1E6; i; i--) { d = new Date('June 1-0000').getMonth()+1 }; Date.now()-t` --> 0.56 us/conversion. `ms = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];` `t = Date.now(); for (i=1E6; i; i--) { d = ms.indexOf('Jul'.toLowerCase())+1 }; Date.now()-t` --> 0.49 us/conversion. Do you really want to use a less flexible JS hack instead of a built-in to save 70 ns? – Denis Howe Oct 22 '21 at 16:19
64

Another way;

alert( "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf("Jun") / 3 + 1 );
Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • 4
    You can extend this idea to full month names (3 char names would still work) like this `'January___February__March_____April_____May_______June______July______August____September_October___November__December__'.indexOf("Jun") / 10 + 1`. _Why 10 chars and not 9?_ So if you want to do the reverse, you can trim with `.indexOf('_')` – Paul S. Nov 26 '12 at 15:11
  • Good hack, but I will not use that in production. A map will be simple and extensible too, so that we can map both "Jan" and "January" to 1. – Deep Jun 23 '14 at 08:46
43

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',
}
adius
  • 13,685
  • 7
  • 45
  • 46
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 1
    I agree that using an object (or Array) is more efficient - but the OP asked for non-array. I know I'll sometimes take the hit on processing time if I can use built in functionality. Parsing a string into a date is something JS does - so creating a function to utilize it makes sense. – Aaron Romine Nov 26 '12 at 14:34
  • @AaronRomine Many native methods available in JavaScript are much faster than what you'd achieve re-writing them using JavaScript, and normally I'd make use of them. However, here OP made no indication of wanting anything other than a simple mapping (which happened to involve month names and numbers) and this is the best way I know. – Paul S. Nov 26 '12 at 15:05
  • somehow I still find this one neat. nothing more nothing less and built just for the intended use. – stucash Jan 29 '21 at 16:43
  • for key value pair you can have this ```export const allMonths = { 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12', }``` – bello hargbola Feb 11 '22 at 01:05
22

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);
YakovL
  • 7,557
  • 12
  • 62
  • 102
Vikas Hardia
  • 2,635
  • 5
  • 34
  • 53
  • 4
    Thanks, but you should add 1 to "month1" in order to get the correct month value. function getMonthFromString(mon){ let month1 = mon.toLowerCase(); let months = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"]; return (months.indexOf(month1)+1); } – AndroLogiciels Nov 16 '19 at 14:41
20

If you are using moment.js:

moment().month("Jan").format("M");
chinupson
  • 6,117
  • 1
  • 16
  • 8
11

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');
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
8

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
qbunt
  • 153
  • 2
  • 8
4
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"));
John Slegers
  • 45,213
  • 22
  • 199
  • 169
2
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])
l2aelba
  • 21,591
  • 22
  • 102
  • 138
2

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;
}
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]);
Erick Garcia
  • 510
  • 5
  • 9
1

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'));
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 24 '21 at 18:37
0

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()];
Liran Barniv
  • 1,320
  • 1
  • 10
  • 10