Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get localized month name using native JS

Tags:

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

like image 359
user779159 Avatar asked Oct 11 '16 08:10

user779159


People also ask

How to get month name in JavaScript?

JavaScript Date getMonth() getMonth() returns the month (0 to 11) of a date.

How do you get the first date of the month from a date in JavaScript?

To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates. Copied! const now = new Date(); const firstDay = new Date(now.


1 Answers

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));
like image 78
k102 Avatar answered Oct 04 '22 04:10

k102