Lavorare con i timestamp Unix in JavaScript
Tutto ciò che ti serve per lavorare con i timestamp Unix in JavaScript — ottenere l'ora attuale, creare Date dai timestamp, formattare per qualsiasi fuso ed evitare gli errori comuni.
Ottenere il timestamp Unix attuale
JavaScript offre diversi modi equivalenti per ottenere l'ora attuale come timestamp numerico. Tutti restituiscono il numero di millisecondi dall'epoch Unix.
- Date.now() → the fastest and most readable — 1700000000000 (milliseconds)
- Math.floor(Date.now() / 1000) → Unix timestamp in seconds — 1700000000
- +new Date() → same as Date.now(), using the unary plus operator
- new Date().getTime() → explicit method call, same result as Date.now()
Creare un oggetto Date da un timestamp Unix
Il costruttore Date accetta millisecondi dall'epoch. Moltiplica sempre per 1000 un timestamp in secondi prima di passarlo al costruttore.
- new Date(1700000000 * 1000) → from seconds (most common case)
- new Date(1700000000000) → from milliseconds (JavaScript APIs, Java)
- new Date(Date.now()) → current time as a Date object
- new Date(0) → the Unix epoch: January 1, 1970 00:00:00 UTC
Formattare le date — metodi di stringa integrati
L'oggetto Date ha diversi metodi integrati di conversione in stringa. Ciascuno produce un formato diverso.
- .toISOString() → '2023-11-15T06:13:20.000Z' — ISO 8601, always UTC, machine-readable
- .toUTCString() → 'Wed, 15 Nov 2023 06:13:20 GMT' — RFC 7231, human-readable UTC
- .toString() → local timezone string with full zone name
- .toLocaleString() → locale-aware format in the user's local timezone
Formattazione con fuso tramite Intl.DateTimeFormat
Per una formattazione delle date coerente e consapevole del fuso senza librerie esterne, usa l'API Intl.DateTimeFormat. È disponibile in tutti i browser moderni e in Node.js 13+.
- new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', dateStyle: 'full', timeStyle: 'long' }).format(date)
- date.toLocaleString('en-GB', { timeZone: 'Europe/London', hour12: false })
- new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai' }).format(date)
- new Intl.DateTimeFormat('en-CA', { timeZone: tz }).formatToParts(date) → array of {type, value} parts for custom layouts
Riconvertire una stringa di data in un timestamp Unix
Per andare nel verso opposto — da una stringa di data a un timestamp Unix — usa Date.parse() o passa la stringa al costruttore Date.
- new Date('2023-11-15T06:13:20Z').getTime() / 1000 → Unix seconds from ISO 8601 UTC
- new Date('2023-11-15T01:13:20-05:00').getTime() → Unix milliseconds from ISO with offset
- Date.parse('2023-11-15T06:13:20Z') → same as new Date(...).getTime()
- Always use ISO 8601 format with explicit timezone for predictable parsing
Errori comuni
Questi sono gli errori più frequenti degli sviluppatori JavaScript con date e timestamp:
- new Date(1700000000) — senza × 1000 si converte nell'anno ~1970 invece del 2023
- getMonth() restituisce 0–11, non 1–12 — aggiungi sempre 1 quando lo mostri
- new Date('2024-01-01') è mezzanotte UTC; new Date('2024/01/01') è mezzanotte locale
- new Date(2024, 0, 1) = 1° gennaio (anche nel costruttore il mese parte da 0)
- Aggiungere 86400000 ms per ottenere «domani» può fallire ai cambi dell'ora legale — usa invece setDate(d.getDate() + 1)
FAQ sui timestamp Unix in JavaScript
- Come ottengo un timestamp Unix in secondi in JavaScript?
- Usa Math.floor(Date.now() / 1000). Date.now() restituisce millisecondi, quindi dividi per 1000 e arrotonda per difetto per ottenere secondi Unix interi.
- Perché new Date() con un timestamp Unix mostra il 1970?
- Il costruttore Date si aspetta millisecondi. Un timestamp in secondi a 10 cifre va moltiplicato per 1000: new Date(seconds * 1000).
- Come formatto una data JavaScript per un fuso specifico?
- Usa Intl.DateTimeFormat con un'opzione timeZone esplicita, come new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York' }). Applica l'ora legale automaticamente e non richiede librerie esterne.