Get localized month name using native JS

守給你的承諾、 提交于 2020-05-08 06:56:48

问题


It's possible to do this to get the localized full month name using native javascript.

var objDate = new Date("10/11/2009"),
    locale = "en-us",
    month = objDate.toLocaleString(locale, { month: "long" });

But this only gets the month number for a given date. I'd simply like to get the month name corresponding to a month number. For example, if I do getMonth(2) it would return February. How can I implement getMonth using native javascript(no libraries like moment)?


回答1:


You are already close:

var getMonth = function(idx) {

  var objDate = new Date();
  objDate.setDate(1);
  objDate.setMonth(idx-1);

  var locale = "en-us",
      month = objDate.toLocaleString(locale, { month: "long" });

    return month;
}

console.log(getMonth(1));
console.log(getMonth(12));


来源:https://stackoverflow.com/questions/39972925/get-localized-month-name-using-native-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!