Get localized month name using native JS
Asked Answered
A

3

35

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

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 (no libraries like moment)?

Anhanhalt answered 11/10, 2016 at 8:9 Comment(1)
It's a 1-line-solution: new Date(2020, monthIndex, 1).toLocaleString("en-us", {month: "long"});Easton
G
65

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));
Gesture answered 11/10, 2016 at 8:13 Comment(3)
Do you know if there's a way to do it without needing to instantiate a date object?Anhanhalt
I wouldn't rely on the language at all: just add an array of month names in your localisation file (or make it if you don't have one).Gesture
I realize that this is a very old answer, but this is one of those cases where it doesn't work properly for February on the 29th, 30th or 31st of another month because the Date object is initialized with the current date. This can be solved by adding objDate.setDate(1); before setting the month.Provo
S
2

To get all the months of a year and days of the week, loop over a set of dates and use toLocaleString with appropriate options to get the required values:

function getLocalDayNames() {
  let d = new Date(2000,0,3); // Monday
  let days = [];
  for (let i=0; i<7; i++) {
    days.push(d.toLocaleString('default',{weekday:'long'}));
    d.setDate(d.getDate() + 1);
  }
  return days;
}

console.log(getLocalDayNames());

function getLocalMonthNames() {
  let d = new Date(2000,0); // January
  let months = [];
  for (let i=0; i<12; i++) {
    months.push(d.toLocaleString('default',{month:'long'}));
    d.setMonth(i + 1);
  }
  return months;
}

console.log(getLocalMonthNames());

The language default means toLocaleString uses the default language of the implementation that the code is running in.

Soliloquize answered 17/3, 2022 at 12:17 Comment(0)
P
2

You can use localization formatting:

const DAYS_IN_WEEK = 7;
const MONTHS_IN_YEAR = 12;

function localizedWeekdayNames(
  locale: Intl.LocalesArgument = "default",
  dateStyle: Intl.RelativeTimeFormatStyle = "short"
): string[] {
  const dayNames: string[] = [];
  const currentDate = new Date();
  while (currentDate.getDay() !== 0) {
    currentDate.setDate(currentDate.getDate() + 1);
  }
  for (let day = 0; day < DAYS_IN_WEEK; day++) {
    dayNames.push(
      currentDate.toLocaleDateString(locale, { weekday: dateStyle })
    );
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return dayNames;
}

function localizedMonthNames(
  locale: Intl.LocalesArgument = "default",
  dateStyle: Intl.RelativeTimeFormatStyle = "short"
): string[] {
  const monthNames: string[] = [];
  const currentDate = new Date();
  while (currentDate.getMonth() !== 0) {
    currentDate.setMonth(currentDate.getMonth() + 1);
  }
  for (let month = 0; month < MONTHS_IN_YEAR; month++) {
    monthNames.push(
      currentDate.toLocaleDateString(locale, { month: dateStyle })
    );
    currentDate.setMonth(currentDate.getMonth() + 1);
  }
  return monthNames;
}

// ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] 
console.log(localizedWeekdayNames());

// ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 
console.log(localizedMonthNames());

Here is the generated JS with some additional localization output.

const DAYS_IN_WEEK = 7;
const MONTHS_IN_YEAR = 12;

function localizedWeekdayNames(locale = "default", dateStyle = "short") {
  const dayNames = [];
  const currentDate = new Date();
  while (currentDate.getDay() !== 0) {
    currentDate.setDate(currentDate.getDate() + 1);
  }
  for (let day = 0; day < DAYS_IN_WEEK; day++) {
    dayNames.push(currentDate.toLocaleDateString(locale, {
      weekday: dateStyle
    }));
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return dayNames;
}

function localizedMonthNames(locale = "default", dateStyle = "short") {
  const monthNames = [];
  const currentDate = new Date();
  while (currentDate.getMonth() !== 0) {
    currentDate.setMonth(currentDate.getMonth() + 1);
  }
  for (let month = 0; month < MONTHS_IN_YEAR; month++) {
    monthNames.push(currentDate.toLocaleDateString(locale, {
      month: dateStyle
    }));
    currentDate.setMonth(currentDate.getMonth() + 1);
  }
  return monthNames;
}

// Sun Mon Tue Wed Thu Fri Sat
console.log(...localizedWeekdayNames());

// Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
console.log(...localizedMonthNames());

// domingo lunes martes miércoles jueves viernes sábado
console.log(...localizedWeekdayNames('es-ES', 'long'));

// enero febrero marzo abril mayo junio
// julio agosto septiembre octubre noviembre diciembre
console.log(...localizedMonthNames('es-ES', 'long'));
Propraetor answered 9/5, 2023 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.