Skip to content Skip to sidebar Skip to footer

Javascript - Convert Number To Month Name

I have a very simple problem but for some reason I can't find the answer for it. label.forEach(function(value){ months.push(value['month']); revenue.push(value['revenue']);

Solution 1:

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

var selectedMonthName = months[value['month']];

look at the links

stack 1

Solution 2:

This can be easily done using moment.js.

var months = [];
months.push(moment().month(0).format("MMMM"));
console.log(months);
<scriptsrc="https://momentjs.com/downloads/moment.min.js"></script>

Solution 3:

Intl.DateTimeFormat('en', { month: 'long' }).format(newDate('1')); // January

Can be achieved using Internationalization API

Solution 4:

    <script src="https://momentjs.com/downloads/moment.min.js"></script>

    var monthNumber='03';
    var month = [ "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December" ];
    var monthIndex = moment().month(monthNumber[1]-1).format("M");
    var selectedMonthName = month[monthIndex-1];
    alert(selectedMonthName);

Solution 5:

another simple way of doing it is with a map, create one like this

const monthNumberToLabelMap = {
  [1]: 'January',
  [2]: 'February',
  [3]: 'March',
  [4]: 'April',
  [5]: 'May',
  [6]: 'June',
  [7]: 'July',
  [8]: 'August',
  [9]: 'September',
  [10]: 'October',
  [11]: 'November',
  [12]: 'December',
}

then use the map in your code like this

label.forEach(function(value){
    months.push(monthNumberToLabelMap[value['month']]);
    revenue.push(value['revenue']);
});

note:

it wasn't clear from your question what the format of your month data is, default javascript months are 0-11 in which case you would have change my map

Post a Comment for "Javascript - Convert Number To Month Name"