Tutorial
So konvertieren Sie Zeitstempel in JavaScript: Vollständiges Tutorial mit Beispielen
Einführung
Das Konvertieren von Zeitstempeln in JavaScript ist eine grundlegende Fähigkeit für Webentwickler. Unabhängig davon, ob Sie mit APIs, Datenbanken oder Benutzeroberflächen arbeiten, müssen Sie häufig zwischen Unix-Zeitstempeln und für Menschen lesbaren Daten konvertieren. Dieses Tutorial führt Sie durch alles, was Sie wissen müssen.
Was Sie lernen werden
- ✅ Aktuelle Zeitstempel abrufen
- ✅ Konvertieren von Zeitstempeln in Datumsobjekte
- ✅ Konvertieren von Datumsobjekten in Zeitstempel
- ✅ Zeitstempel für die Anzeige formatieren
- ✅ Umgang mit unterschiedlichen Zeitstempelgenauigkeiten
- ✅ Arbeiten mit Zeitzonen
- ✅ Häufige Fallstricke und wie man sie vermeidet
Voraussetzungen
Sie benötigen lediglich grundlegende JavaScript-Kenntnisse. Für dieses Tutorial sind keine externen Bibliotheken erforderlich (obwohl wir am Ende einige beliebte erwähnen).
Schritt 1: Aktuellen Zeitstempel abrufen
Der einfachste Vorgang besteht darin, die aktuelle Uhrzeit als Zeitstempel abzurufen.
Methode 1: Date.now() (empfohlen)
// Get current timestamp in milliseconds
const timestamp = Date.now();
console.log(timestamp);
// Output: 1704067200000 (13 digits)
Warum das verwenden?
- ✅ Schnellste Methode
- ✅ Es ist nicht erforderlich, ein Datumsobjekt zu erstellen
- ✅ Am häufigsten verwendet
Methode 2: new Date().getTime()
// Create Date object and get timestamp
const timestamp = new Date().getTime();
console.log(timestamp);
// Output: 1704067200000 (13 digits)
Wann sollte dies verwendet werden?
- Wenn Sie bereits über ein Date-Objekt verfügen
- Wenn Sie Methoden verketten müssen
Methode 3: Unärer Plusoperator
// Shorthand using unary plus
const timestamp = +new Date();
console.log(timestamp);
// Output: 1704067200000 (13 digits)
Wann sollte dies verwendet werden?
- Code-Golf oder wenn es auf Kürze ankommt
- Nicht für Anfänger empfohlen (weniger lesbar)
Zeitstempel in Sekunden erhalten
JavaScript verwendet standardmäßig Millisekunden, aber viele APIs verwenden Sekunden:
// Get timestamp in seconds (10 digits)
const timestampInSeconds = Math.floor(Date.now() / 1000);
console.log(timestampInSeconds);
// Output: 1704067200 (10 digits)
// Alternative: Using parseInt
const timestampSec = parseInt(Date.now() / 1000);
console.log(timestampSec);
// Output: 1704067200
Schritt 2: Zeitstempel in Datum konvertieren
Konvertieren eines Unix-Zeitstempels in ein JavaScript-Datumsobjekt.
Grundlegende Konvertierung
// Millisecond timestamp (13 digits)
const timestamp = 1704067200000;
const date = new Date(timestamp);
console.log(date);
// Output: Mon Jan 01 2024 00:00:00 GMT+0000 (UTC)
console.log(date.toISOString());
// Output: 2024-01-01T00:00:00.000Z
Zweite Zeitstempel konvertieren
Viele APIs geben Zeitstempel in Sekunden (10 Ziffern) zurück, nicht in Millisekunden:
// Second timestamp (10 digits) - MUST multiply by 1000!
const timestampInSeconds = 1704067200;
const date = new Date(timestampInSeconds * 1000);
console.log(date.toISOString());
// Output: 2024-01-01T00:00:00.000Z
⚠️ Häufiger Fehler:
// ❌ WRONG: Using seconds directly
const wrongDate = new Date(1704067200);
console.log(wrongDate.toISOString());
// Output: 1970-01-20T17:27:47.200Z (WRONG!)
// ✅ CORRECT: Multiply by 1000
const correctDate = new Date(1704067200 * 1000);
console.log(correctDate.toISOString());
// Output: 2024-01-01T00:00:00.000Z (CORRECT!)
Zeitstempelpräzision ermitteln
Hilfsfunktion zur automatischen Erkennung, ob der Zeitstempel in Sekunden oder Millisekunden angegeben ist:
function createDateFromTimestamp(timestamp) {
// If timestamp has 10 digits, it's in seconds
// If timestamp has 13 digits, it's in milliseconds
const digitCount = timestamp.toString().length;
if (digitCount === 10) {
// Seconds - multiply by 1000
return new Date(timestamp * 1000);
} else if (digitCount === 13) {
// Milliseconds - use directly
return new Date(timestamp);
} else {
throw new Error(`Invalid timestamp: ${timestamp}`);
}
}
// Usage
const date1 = createDateFromTimestamp(1704067200); // 10 digits (seconds)
const date2 = createDateFromTimestamp(1704067200000); // 13 digits (milliseconds)
console.log(date1.toISOString()); // 2024-01-01T00:00:00.000Z
console.log(date2.toISOString()); // 2024-01-01T00:00:00.000Z
Schritt 3: Datum in Zeitstempel konvertieren
Konvertieren eines JavaScript-Datumsobjekts zurück in einen Unix-Zeitstempel.
Ab aktuellem Datum
const now = new Date();
// Get timestamp in milliseconds
const timestampMs = now.getTime();
console.log(timestampMs); // 1704067200000
// Get timestamp in seconds
const timestampSec = Math.floor(now.getTime() / 1000);
console.log(timestampSec); // 1704067200
Von einer bestimmten Datumszeichenfolge
// ISO 8601 format (recommended)
const date1 = new Date('2024-01-01T00:00:00Z');
console.log(date1.getTime()); // 1704067200000
// Different date formats
const date2 = new Date('January 1, 2024');
const date3 = new Date('01/01/2024');
const date4 = new Date('2024-01-01');
console.log(date2.getTime()); // Depends on local timezone
console.log(date3.getTime()); // Depends on local timezone
console.log(date4.getTime()); // Usually 00:00:00 in local timezone
⚠️ Wichtig: Verschiedene Datumszeichenfolgenformate verhalten sich bei Zeitzonen unterschiedlich!
Aus Datumskomponenten
// Create date from year, month, day, etc.
// Note: Month is 0-indexed (0 = January, 11 = December)
const date = new Date(2024, 0, 1, 0, 0, 0); // Jan 1, 2024, 00:00:00
const timestamp = date.getTime();
console.log(timestamp); // Local timezone timestamp
// For UTC, use Date.UTC()
const utcTimestamp = Date.UTC(2024, 0, 1, 0, 0, 0);
console.log(utcTimestamp); // 1704067200000 (UTC)
Schritt 4: Zeitstempel formatieren
Konvertieren von Zeitstempeln in für Menschen lesbare Formate.
Integrierte JavaScript-Methoden
const date = new Date(1704067200000);
// ISO 8601 format (best for APIs)
console.log(date.toISOString());
// Output: "2024-01-01T00:00:00.000Z"
// Locale-specific date string
console.log(date.toLocaleDateString());
// Output: "1/1/2024" (US) or "01/01/2024" (UK)
// Locale-specific date and time
console.log(date.toLocaleString());
// Output: "1/1/2024, 12:00:00 AM"
// Locale-specific time
console.log(date.toLocaleTimeString());
// Output: "12:00:00 AM"
// Full date string
console.log(date.toDateString());
// Output: "Mon Jan 01 2024"
// UTC string
console.log(date.toUTCString());
// Output: "Mon, 01 Jan 2024 00:00:00 GMT"
Benutzerdefinierte Formatierung
function formatTimestamp(timestamp, format = 'full') {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
const formats = {
'full': `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
'date': `${year}-${month}-${day}`,
'time': `${hours}:${minutes}:${seconds}`,
'short': `${month}/${day}/${year}`,
'iso': date.toISOString()
};
return formats[format] || formats.full;
}
// Usage
const timestamp = 1704067200000;
console.log(formatTimestamp(timestamp, 'full')); // "2024-01-01 00:00:00"
console.log(formatTimestamp(timestamp, 'date')); // "2024-01-01"
console.log(formatTimestamp(timestamp, 'time')); // "00:00:00"
console.log(formatTimestamp(timestamp, 'short')); // "01/01/2024"
Verwendung von Intl.DateTimeFormat (moderner Ansatz)
const timestamp = 1704067200000;
const date = new Date(timestamp);
// US English format
const usFormatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
console.log(usFormatter.format(date));
// Output: "January 1, 2024 at 12:00 AM"
// Custom format
const customFormatter = new Intl.DateTimeFormat('en-US', {
weekday: 'long',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
});
console.log(customFormatter.format(date));
// Output: "Monday, Jan 1, 2024, 12:00:00 AM UTC"
Schritt 5: Arbeiten mit Zeitzonen
Der Umgang mit unterschiedlichen Zeitzonen ist für eine genaue Zeitstempelkonvertierung von entscheidender Bedeutung.
UTC vs. Ortszeit
const timestamp = 1704067200000; // Jan 1, 2024, 00:00:00 UTC
const date = new Date(timestamp);
// Get UTC components
console.log('UTC Year:', date.getUTCFullYear()); // 2024
console.log('UTC Month:', date.getUTCMonth() + 1); // 1
console.log('UTC Date:', date.getUTCDate()); // 1
console.log('UTC Hours:', date.getUTCHours()); // 0
// Get local components (depends on your timezone)
console.log('Local Year:', date.getFullYear()); // 2024
console.log('Local Month:', date.getMonth() + 1); // 1 (or different)
console.log('Local Date:', date.getDate()); // 1 (or different)
console.log('Local Hours:', date.getHours()); // 0 (or different)
Konvertieren in eine bestimmte Zeitzone
const timestamp = 1704067200000;
const date = new Date(timestamp);
// Display in different timezones using Intl.DateTimeFormat
const timezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo'];
timezones.forEach(tz => {
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: tz,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
});
console.log(`${tz}:`, formatter.format(date));
});
// Output:
// America/New_York: 12/31/2023, 07:00:00 PM EST
// Europe/London: 01/01/2024, 12:00:00 AM GMT
// Asia/Tokyo: 01/01/2024, 09:00:00 AM JST
Zeitzonenversatz
const date = new Date();
// Get timezone offset in minutes
const offsetMinutes = date.getTimezoneOffset();
console.log('Offset in minutes:', offsetMinutes); // e.g., -480 for UTC+8
// Convert to hours
const offsetHours = -offsetMinutes / 60;
console.log('Offset in hours:', offsetHours); // e.g., 8 for UTC+8
// Format offset as string
const sign = offsetHours >= 0 ? '+' : '-';
const hours = String(Math.abs(Math.floor(offsetHours))).padStart(2, '0');
const minutes = String(Math.abs((offsetHours % 1) * 60)).padStart(2, '0');
console.log(`UTC${sign}${hours}:${minutes}`); // e.g., "UTC+08:00"
Schritt 6: Häufige Fallstricke und Lösungen
Falle 1: Sekunden vs. Millisekunden
// ❌ WRONG: Assuming all timestamps are in milliseconds
const wrongDate = new Date(1704067200); // Treats as milliseconds
console.log(wrongDate.toISOString()); // 1970-01-20T17:27:47.200Z (WRONG!)
// ✅ CORRECT: Check and convert properly
const secondsTimestamp = 1704067200;
const correctDate = new Date(secondsTimestamp * 1000);
console.log(correctDate.toISOString()); // 2024-01-01T00:00:00.000Z (CORRECT!)
Fallstrick 2: Der Monat ist nullindiziert
// ❌ WRONG: Using 1-12 for months
const wrongDate = new Date(2024, 1, 1); // Creates Feb 1, not Jan 1
console.log(wrongDate.toDateString()); // Thu Feb 01 2024
// ✅ CORRECT: Use 0-11 for months
const correctDate = new Date(2024, 0, 1); // Creates Jan 1
console.log(correctDate.toDateString()); // Mon Jan 01 2024
Fallstrick 3: Zeitzonenprobleme mit Datumszeichenfolgen
// Different string formats behave differently!
// ISO 8601 with 'Z' - always UTC
const utcDate = new Date('2024-01-01T00:00:00Z');
console.log(utcDate.toISOString()); // 2024-01-01T00:00:00.000Z
// ISO 8601 without 'Z' - treated as local timezone
const localDate = new Date('2024-01-01T00:00:00');
console.log(localDate.toISOString()); // Depends on your timezone
// Date-only format - treated as local timezone at midnight
const dateOnly = new Date('2024-01-01');
console.log(dateOnly.toISOString()); // Usually local midnight
// ✅ BEST PRACTICE: Always use ISO 8601 with 'Z' for UTC
const safeDate = new Date('2024-01-01T00:00:00.000Z');
Falle 4: Ungültige Daten
// Invalid dates can cause silent errors
const invalidDate = new Date('not a date');
console.log(invalidDate); // Invalid Date
console.log(invalidDate.getTime()); // NaN
// ✅ BEST PRACTICE: Always validate
function isValidDate(date) {
return date instanceof Date && !isNaN(date.getTime());
}
const date1 = new Date('2024-01-01');
const date2 = new Date('invalid');
console.log(isValidDate(date1)); // true
console.log(isValidDate(date2)); // false
Schritt 7: Praxisbeispiele
Beispiel 1: Format „Vor Zeit“ anzeigen
function timeAgo(timestamp) {
const now = Date.now();
const secondsAgo = Math.floor((now - timestamp) / 1000);
if (secondsAgo < 60) {
return `${secondsAgo} seconds ago`;
} else if (secondsAgo < 3600) {
const minutes = Math.floor(secondsAgo / 60);
return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
} else if (secondsAgo < 86400) {
const hours = Math.floor(secondsAgo / 3600);
return `${hours} hour${hours > 1 ? 's' : ''} ago`;
} else {
const days = Math.floor(secondsAgo / 86400);
return `${days} day${days > 1 ? 's' : ''} ago`;
}
}
// Usage
console.log(timeAgo(Date.now() - 30000)); // "30 seconds ago"
console.log(timeAgo(Date.now() - 300000)); // "5 minutes ago"
console.log(timeAgo(Date.now() - 7200000)); // "2 hours ago"
console.log(timeAgo(Date.now() - 172800000)); // "2 days ago"
Beispiel 2: API-Antworthandler
// Typical API response with timestamps
const apiResponse = {
created_at: 1704067200, // Seconds
updated_at: 1704153600000, // Milliseconds (mixed precision!)
expires_at: "2024-01-10T00:00:00Z" // ISO 8601 string
};
// Convert all to Date objects
function parseApiTimestamps(response) {
return {
created: new Date(response.created_at * 1000), // Convert seconds
updated: new Date(response.updated_at), // Already milliseconds
expires: new Date(response.expires_at) // Parse ISO string
};
}
const dates = parseApiTimestamps(apiResponse);
console.log('Created:', dates.created.toLocaleDateString());
console.log('Updated:', dates.updated.toLocaleDateString());
console.log('Expires:', dates.expires.toLocaleDateString());
Beispiel 3: Datumsbereichsvalidator
function isWithinRange(timestamp, startDate, endDate) {
const date = new Date(timestamp);
const start = new Date(startDate);
const end = new Date(endDate);
return date >= start && date <= end;
}
// Usage
const eventTimestamp = 1704067200000; // Jan 1, 2024
const rangeStart = '2024-01-01';
const rangeEnd = '2024-12-31';
console.log(isWithinRange(eventTimestamp, rangeStart, rangeEnd)); // true
Beliebte Bibliotheken für fortgeschrittene Anwendungsfälle
Berücksichtigen Sie für Produktionsanwendungen die folgenden Bibliotheken:
date-fns (empfohlen)
import { format, parseISO, formatDistance } from 'date-fns';
// Format timestamp
const timestamp = 1704067200000;
const formatted = format(timestamp, 'PPP');
console.log(formatted); // "Jan 1st, 2024"
// Time ago
const distance = formatDistance(timestamp, Date.now(), { addSuffix: true });
console.log(distance); // "2 days ago"
Luxon (Modern, Zeitzonenbewusst)
import { DateTime } from 'luxon';
// From timestamp
const dt = DateTime.fromMillis(1704067200000);
console.log(dt.toISO()); // "2024-01-01T00:00:00.000Z"
// Timezone conversion
const tokyo = dt.setZone('Asia/Tokyo');
console.log(tokyo.toFormat('yyyy-MM-dd HH:mm:ss'));
Zusammenfassung
Sie haben gelernt, wie man:
- ✅ Erhalten Sie aktuelle Zeitstempel mit
Date.now() - ✅ Konvertieren Sie Zeitstempel in Datumsobjekte
- ✅ Konvertieren Sie Datumsobjekte zurück in Zeitstempel
- ✅ Datumsangaben für die Anzeige formatieren
- ✅ Behandeln Sie unterschiedliche Zeitstempelgenauigkeiten
- ✅ Arbeiten Sie mit Zeitzonen
- ✅ Vermeiden Sie häufige Fallstricke
Verwandte Tools
Praktizieren Sie das Gelernte mit unseren kostenlosen Tools:
- Unix Timestamp Converter – Interaktive Zeitstempelkonvertierung
- Aktueller Zeitstempel – Erhalten Sie die aktuelle Zeit in verschiedenen Formaten – JavaScript Timestamp Helper – JavaScript-spezifische Tools
- Batch Timestamp Converter – Konvertieren Sie mehrere Zeitstempel
Nächste Schritte
- Erfahren Sie mehr über [Zeitstempel-Präzisionsstufen] (/guides/timestamp-precision-levels)
- Entdecken Sie [Zeitzonen verstehen] (/guides/understanding-timezones)
- Lesen Sie mehr über Das Jahr-2038-Problem
Letzte Aktualisierung: Januar 2025