0

In java script given a month like "October"

how do I convert to a month to number format?

Output should be "10", for example.

i have variable called monthName it is giving value as "october",

now how can i convert monthName value as 10

Manjunath Siddappa
  • 2,126
  • 2
  • 21
  • 40

3 Answers3

4

It's a bit of a hack, but:

var monthName = "October";
var monthNumber = new Date(monthName + " 1").getMonth() + 1;
console.log(monthNumber); // 10;
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
2

Perhaps it's overkill if this is the only work that you will be doing with dates but you could use the moment.js library:

moment("October", "MMM").format("M")

Output:

10

Obviously, you can use the name of a variable instead of the string literal "October".

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
1

You can just do this

function getMonthName() {
    getMonthName.mnths = getMonthName.mnths ||  ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
    return (getMonthName.mnths.indexOf(monthName.toLowerCase()) + 1);
}
console.log(getMonthName("October")); // 10

Just create an array of months, and add one to the index of the month you're trying to find.


This method is lot more efficient than using Date object, as the array of month names is cached and only a look up is done, instead of creating a whole new Date object with unnecessary properties.

This solution is 34% faster than using Date object. This solution DOES NOT allow for terms such as Oct and doesn't care for locales, but that isn't asked for, anyway. If you need them, go with Date object.

Also, this is among the good solutions as new Date("October 1").getMonth() + 1 will give you NaN in IE10 & 11(The latest of the IEs) and even in the latest Mozilla Firefox.

This solution is cross-browser compatible, is more efficient, and certainly not a bad way of solving the problem. JS Perf

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • sorry for unclear i have variable called monthName it is giving value as "october", now how can i convert monthName value as 10 – Manjunath Siddappa Oct 16 '14 at 17:09
  • 1
    Please don't do this. Use a Date object. This is what it's there for. It also has the advantage of being case insensitive, understanding the month abbreviations, and being locale aware. – Ian McLaird Oct 16 '14 at 17:26