将.getMonth转换为javaScript中的字符串month(将0转换为jan)

时间:2019-01-22 06:44:51

标签: javascript arrays

我有月份和数组列表。 var month具有日期月份数。想要将该数字转换为字母。

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);

}

5 个答案:

答案 0 :(得分:2)

您可以通过m[month]

访问月份

答案 1 :(得分:1)

只需使用getMonth()的结果作为索引来访问月份名称数组。

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() } });


或者,您可以完全放弃月份数组并使用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() } });

答案 2 :(得分:1)

loginLink

使用索引获取月份

答案 3 :(得分:0)

由于Date.getMonth()返回一个与该月的从零开始的索引相对应的数字,因此您可以简单地使用该数字来访问数组(m)中的该索引。

const monthName = m[month]

答案 4 :(得分:0)

indexOf是您需要的功能。 这是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 );
  }