Date.prototype.getMonth()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Die getMonth()
Methode von Date
Instanzen gibt den Monat für dieses Datum gemäß der Ortszeit als nullbasierten Wert zurück (wobei null den ersten Monat des Jahres anzeigt).
Probieren Sie es aus
const moonLanding = new Date("July 20, 69 00:20:18");
console.log(moonLanding.getMonth()); // (January gives 0)
// Expected output: 6
Syntax
getMonth()
Parameter
Keine.
Rückgabewert
Eine Ganzzahl zwischen 0 und 11, die den Monat für das angegebene Datum gemäß der Ortszeit darstellt: 0 für Januar, 1 für Februar und so weiter. Gibt NaN
zurück, wenn das Datum ungültig ist.
Beschreibung
Der Rückgabewert von getMonth()
ist nullbasiert, was nützlich ist, um in Arrays von Monaten zu indexieren, zum Beispiel:
const valentines = new Date("1995-02-14");
const month = valentines.getMonth();
const monthNames = ["January", "February", "March" /* , … */];
console.log(monthNames[month]); // "February"
Für den Zweck der Internationalisierung sollten Sie jedoch bevorzugt Intl.DateTimeFormat
mit dem options
Parameter verwenden.
const options = { month: "long" };
console.log(new Intl.DateTimeFormat("en-US", options).format(valentines));
// "February"
console.log(new Intl.DateTimeFormat("de-DE", options).format(valentines));
// "Februar"
Beispiele
Verwendung von getMonth()
Die Variable month
hat den Wert 11
, basierend auf dem Wert des Date
Objekts xmas95
.
const xmas95 = new Date("1995-12-25T23:15:30");
const month = xmas95.getMonth();
console.log(month); // 11
Spezifikationen
Specification |
---|
ECMAScript® 2026 Language Specification # sec-date.prototype.getmonth |