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 Methode getMonth()
von Date
-Instanzen gibt den Monat dieses Datums gemäß der lokalen Zeit als nullbasierten Wert zurück (wobei null den ersten Monat des Jahres angibt).
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
Ein Integer-Wert zwischen 0 und 11, der den Monat für das angegebene Datum gemäß der lokalen Zeit repräsentiert: 0 für Januar, 1 für Februar usw. Gibt NaN
zurück, wenn das Datum ungültig ist.
Beschreibung
Der Rückgabewert von getMonth()
ist nullbasiert, was nützlich ist, um beispielsweise auf Arrays von Monaten zuzugreifen:
const valentines = new Date("1995-02-14");
const month = valentines.getMonth();
const monthNames = ["January", "February", "March" /* , … */];
console.log(monthNames[month]); // "February"
Falls Sie jedoch die Internationalisierung berücksichtigen möchten, sollten Sie stattdessen 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® 2025 Language Specification # sec-date.prototype.getmonth |
Browser-Kompatibilität
BCD tables only load in the browser