1
\$\begingroup\$

The following script uses a switch statement to determine the numeric month based on the actual month. Is there a more succinct way (read: elegant, or less time to write) to accomplish the same result? Is there a down-side or up-side to either approach?

jsFiddle

var month = "May"; 
            var m;
            switch(month) {
                case "January":
                    m = 0;
                    break;
                case "February":
                    m = 1;
                    break;
                case "March":
                    m = 2;
                    break;
                case "April":
                    m = 3;
                    break;
                case "May":
                    m = 4;
                    break;
                case "June":
                    m = 5;
                    break;
                case "July":
                    m = 6;
                    break;
                case "August":
                    m = 7;
                    break;
                case "September":
                    m = 8;
                    break;
                case "October":
                    m = 9;
                    break;
                case "November":
                    m = 10;
                    break;
                case "December":
                    m = 11;
                    break;
                default:
                //
            }
        console.log(m);      
\$\endgroup\$
0

3 Answers 3

7
\$\begingroup\$

Just use an array.

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var m = months.indexOf('May');  // 4
\$\endgroup\$
0
2
\$\begingroup\$

Or instead of an array, work it out from the date... no need for messy arrays

function getMonthFromString(monthName){

   var d = Date.parse(mon + "1, 2000");
   if( !isNaN(d) )
    {
      return new Date(d).getMonth();
   }
   return -1;
}
\$\endgroup\$
0
1
\$\begingroup\$

Just have your month names in an array and use indexOf to grab the index.

var monthnames = ['Jan', 'Feb', 'Mar', 'Apr']; // etc
var month = 'Mar';
var monthno = monthnames.indexOf(month);
console.log(monthno) // 2
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.