Auf dieser Seite sind verschiedene JavaScript Snippets zu Date und Verwendung von Datum-Objekten.

Die Snippets stellen Beispiele dar. Passe diese gerne für deine Zwecke an. Es handelt sich hierbei nicht um vollständige Dokumentationen. Diese sind an einer anderen Stelle dokumentiert.

Aktuelles Datum erhalten

JavaScript
let currentDate = new Date();
let formattedDate = currentDate.toLocaleDateString("de-DE");
console.log(`Current date: ${formattedDate}`);
Output
Current date: 27.4.2025

Datum in Zeitstempel umwandeln

JavaScript
const currentDate = new Date();
const timestampVersion = currentDate.getTime();

console.log("Current date:", currentDate);
console.log("Timestamp:", timestampVersion);
Output
Current date: 2025-04-27T19:27:10.411Z
Timestamp: 1745782030411

Datum Formatierung

JavaScript
let currentDate = new Date();

let formattedDate = currentDate.toLocaleDateString("de-De", {
    year: "numeric",
    month: "long",
    day: "numeric",
    weekday: "long",
    timeZone: "UTC"
});

console.log(`Formated date: ${formattedDate}`);
Output
Formated date: Sonntag, 27. April 2025

Datum Countdown

Falls ihr dieses Beispiel ausprobieren wollt, passt bitte das Datum so an, dass es in Zukunft liegt, damit die Funktion korrekt funktioniert.

JavaScript
const targetDate = new Date("2025-05-05 00:00:00").getTime();
const countdownInterval = setInterval(updateCountdown, 1000);

function updateCountdown() {
    const currentDate = new Date().getTime();
    const timeDiff  = targetDate - currentDate;

    const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
    const hours = Math.floor(
        (timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
    );
    const minutes = Math.floor(
        (timeDiff % (1000 * 60 * 60)) / (1000 * 60)
    );
    const seconds = Math.floor(
        (timeDiff % (1000 * 60)) / 1000
    );

    if (timeDiff <= 0) {
        clearInterval(updateCountdown);
    } else {
        console.log(`${days} | ${hours} | ${minutes} | ${seconds}`);
    }
}
Output
7 | 2 | 28 | 54
7 | 2 | 28 | 53
7 | 2 | 28 | 52
7 | 2 | 28 | 51
7 | 2 | 28 | 50
7 | 2 | 28 | 49
7 | 2 | 28 | 48

Zwei Daten vergleichen

JavaScript
let dateOne = "2024-01-01";
let dateTwo = "2025-01-01";

if (dateOne < dateTwo) {
    console.log(`${dateOne} < ${dateTwo}`);
} else if (dateOne > dateTwo) {
    console.log(`${dateOne} > ${dateTwo}`);
} else {
    console.log(`${dateOne} = ${dateTwo}`);
}
Output
2024-01-01 < 2025-01-01
/ Weiter

Zurück zu Snippets

Zur Übersicht