-1

i have the month and the array list. var month has the date month number. wanted to convert that number to alphabet.

function setDate(data){
    var d = new Date(data.event_details.event_start_date);
    var month = d.getMonth();
    var m = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

    console.log(m);

}
tomerpacific
  • 4,704
  • 13
  • 34
  • 52

5 Answers5

2

Just access the array of month names using the result of getMonth() as the index.

function setDate(data){
  const date = new Date(data.event_details.event_start_date);
  const months = [
    "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
  ];
  console.log(months[date.getMonth()]);
}

setDate({ event_details: { event_start_date: Date.now() } });

Alternatively, you can ditch the months array altogether and use toLocaleDateString.

function setDate(data) {
  const date = new Date(data.event_details.event_start_date);
  const month = date.toLocaleDateString("en-US", { month: 'short' });
  
  console.log(month);
}

setDate({ event_details: { event_start_date: Date.now() } });
Callam
  • 11,409
  • 2
  • 34
  • 32
2

You can access the month by m[month]

Umair Farooq
  • 1,763
  • 13
  • 16
2
  function setDate(data){
    var d = new Date(data.event_details.event_start_date); 
    var month = d.getMonth();
    var m =  ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    console.log(m[month]);
  }

Use the index to get month

sridhar..
  • 1,945
  • 15
  • 19
0

Because Date.getMonth() returns a number corresponding to the zero-based index of the month, you can simply use that number to access that index in your array (m).

const monthName = m[month]
Ben Steward
  • 2,338
  • 1
  • 13
  • 23
0

indexOf is the function you need. Here is the codepen link

function setDate(data){
    var d = new Date(data.event_details.event_start_date);
    var month = d.getMonth();
    var m = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    var monthName=m[month];
    console.log("month= " +monthName );
  }
Prashant Zombade
  • 482
  • 3
  • 15