Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten switch case block converting a number to a month name?

Is there a way to write this on fewer lines, but still easily readable?

var month = '';  switch(mm) {     case '1':         month = 'January';         break;     case '2':         month = 'February';         break;     case '3':         month = 'March';         break;     case '4':         month = 'April';         break;     case '5':         month = 'May';         break;     case '6':         month = 'June';         break;     case '7':         month = 'July';         break;     case '8':         month = 'August';         break;     case '9':         month = 'September';         break;     case '10':         month = 'October';         break;     case '11':         month = 'November';         break;     case '12':         month = 'December';         break; } 
like image 600
Leon Gaban Avatar asked Apr 23 '15 15:04

Leon Gaban


2 Answers

Define an array, then get by index.

var months = ['January', 'February', ...];  var month = months[mm - 1] || ''; 
like image 101
xdazz Avatar answered Sep 20 '22 15:09

xdazz


what about not to use array at all :)

var objDate = new Date("10/11/2009"),     locale = "en-us",     month = objDate.toLocaleString(locale, { month: "long" });  console.log(month);  // or if you want the shorter date: (also possible to use "narrow" for "O" console.log(objDate.toLocaleString(locale, { month: "short" })); 

as per this answer Get month name from Date from David Storey

like image 34
vidriduch Avatar answered Sep 17 '22 15:09

vidriduch