← Tutti gli articoli

Millisecondi vs secondi: come convertire i millis in un timestamp Unix

Il bug di timestamp più comune è passare millisecondi dove ci si aspettano secondi, o viceversa. Impara la regola delle 10 vs 13 cifre, i default dei linguaggi, le implicazioni per i database e i pattern di conversione sicuri.

Perché esistono due standard

Il tempo Unix è stato originariamente definito in secondi: un intero sembrava naturale per un sistema che si incrementava a ogni tic di clock. L'oggetto Date di JavaScript, introdotto nel 1995, scelse i millisecondi per gestire la temporizzazione di eventi sotto il secondo nel browser. Molti database e linguaggi backend mantennero i secondi Unix come default. Oggi entrambi gli standard coesistono in ogni codice che attraversa il confine JavaScript-server, ed è per questo che un valore può sembrare valido e rappresentare comunque una data a decine di migliaia di anni.

Quale unità usa ogni linguaggio

Il modo più sicuro per ricordare la divisione: le API Date del browser di solito vogliono millisecondi, le API server in stile Unix di solito espongono secondi, e le librerie di tempo più recenti spesso offrono entrambi. Non dedurre l'unità dal solo linguaggio leggendo la documentazione di un'API di terze parti; controlla la descrizione del campo e gli esempi.

  • Milliseconds: JavaScript Date.now(), Java System.currentTimeMillis(), Java Instant.toEpochMilli(), .NET ToUnixTimeMilliseconds()
  • Seconds: Python time.time() (float), PHP time(), Go time.Now().Unix(), Ruby Time.now.to_i, C time(NULL), PostgreSQL EXTRACT(EPOCH)
  • Both: Rust — duration.as_secs() for seconds, duration.as_millis() for milliseconds
  • Python note: time.time() returns a float, so milliseconds are available as int(time.time() * 1000)

Riconoscere l'unità dal valore

Un'euristica affidabile per le date moderne: un numero a 10 cifre è in secondi; a 13 cifre è in millisecondi. I secondi Unix attuali sono intorno a 1,7–2,1 miliardi (10 cifre) e non raggiungeranno 13 cifre fino all'anno 33658. I millisecondi Unix attuali hanno già 13 cifre. L'euristica è più forte dagli anni 2000 fino a qualche migliaio di anni avanti; per date storiche, negative o fixture di test compatte, usa unità esplicite invece di indovinare.

  • valore a 10 cifre → secondi (es. 1700000000 = 2023-11-14 UTC)
  • valore a 13 cifre → millisecondi (es. 1700000000000 = 2023-11-14 UTC)
  • valore a 16 cifre → microsecondi (dividi per 1,000,000 per i secondi)
  • valore negativo → data prima del 1° gennaio 1970 (secondi o millisecondi)

Pattern di conversione sicuri

La conversione in sé è semplice aritmetica; la parte difficile è scegliere dove farla. Converti al confine del sistema, dai un nome al valore convertito ed evita di passare numeri grezzi ambigui attraverso più livelli.

  • Seconds to milliseconds: seconds * 1000
  • Milliseconds to whole seconds — JavaScript: Math.floor(ms / 1000)
  • Milliseconds to whole seconds — Python: ms // 1000
  • Milliseconds to whole seconds — Go: ms / 1000 (integer division)
  • Universal guard in JavaScript: const toMs = ts => ts < 1e11 ? ts * 1000 : ts

Come compaiono i bug di unità in produzione

Un bug secondi-vs-millisecondi spesso sopravvive alla validazione perché entrambi i valori sono solo numeri. Compare di solito più tardi come una data impossibile: gennaio 1970 in JavaScript quando i secondi sono stati trattati come millisecondi, o un anno molto lontano quando un backend ha trattato i millisecondi come secondi.

  • Data del 1970 nella UI JavaScript → secondi passati a new Date() senza moltiplicare per 1000
  • Anno 50000+ in Python, Go o PHP → millisecondi passati a un'API che si aspettava secondi
  • Token scaduti che non scadono mai → timestamp di scadenza salvato nell'unità sbagliata
  • Voci di cache che spariscono subito → millisecondi divisi due volte o secondi moltiplicati due volte
  • Grafici di analytics con intervalli vuoti → i limiti della query usano un'unità diversa dai timestamp degli eventi salvati

Convenzioni di denominazione per API e database

Una piccola convenzione di denominazione evita la maggior parte di questi bug. Non pubblicare mai un campo API chiamato timestamp a meno che la documentazione non sia eccezionalmente chiara. Preferisci nomi di campo che includano significato e unità.

  • createdAtMs — Unix milliseconds, best for JavaScript clients
  • createdAtSeconds — Unix seconds, common for backend services
  • createdAtIso — ISO 8601 string, useful for human-readable API responses
  • expiresAtUnixSeconds — explicit enough for auth tokens and signed URLs
  • event_time TIMESTAMPTZ — native database time, with conversion handled by the database

FAQ millisecondi vs secondi

A tiny naming convention prevents most of these bugs. Never publish an API field called timestamp unless the documentation is unusually clear. Prefer field names that include both meaning and unit.

  • createdAtMs — Unix milliseconds, best for JavaScript clients
  • createdAtSeconds — Unix seconds, common for backend services
  • createdAtIso — ISO 8601 string, useful for human-readable API responses
  • expiresAtUnixSeconds — explicit enough for auth tokens and signed URLs
  • event_time TIMESTAMPTZ — native database time, with conversion handled by the database

Microseconds (16 digits) and nanoseconds (19 digits)

Most production timestamps are seconds (10 digits) or milliseconds (13 digits), but two higher-precision formats also appear in real systems — microseconds and nanoseconds. The same digit-counting rule extends.

  • 10 digits ≈ Unix seconds (~1.7×10⁹ today)
  • 13 digits ≈ Unix milliseconds (~1.7×10¹²)
  • 16 digits ≈ Unix microseconds (~1.7×10¹⁵) — Python time.time_ns()/1000, Postgres TIMESTAMP precision 6
  • 19 digits ≈ Unix nanoseconds (~1.7×10¹⁸) — Java Instant.toEpochNano(), Go time.UnixNano(), Temporal.Instant.epochNanoseconds
  • PostgreSQL to_timestamp() takes seconds with an optional fractional part; passing milliseconds yields a date around the year 55000
  • Convert from any precision to milliseconds via integer arithmetic before doing further math
  • Silent truncation: if a database column has millisecond precision but you store nanoseconds, the bottom 6 digits are dropped on insert

How many microseconds in a second? 1 second to milliseconds, microseconds to milliseconds

A quick reference for the unit math that drives every seconds/milliseconds/microseconds bug. The questions "how many microseconds in a second", "1 second to milliseconds", and "microseconds to milliseconds" are all powers of 1000 — but every order of magnitude is one place where production code goes wrong. Keep the table below within reach when writing high-resolution timestamp code.

  • 1 second to milliseconds = 1,000 ms (10³)
  • How many microseconds in a second? = 1,000,000 µs (10⁶)
  • 1 second to nanoseconds = 1,000,000,000 ns (10⁹)
  • Microseconds to milliseconds = µs ÷ 1,000 (10³ step down)
  • Milliseconds to microseconds = ms × 1,000
  • Nanoseconds to microseconds = ns ÷ 1,000
  • Common precision: JavaScript Date.now() = ms, performance.now() = sub-ms float, Go time.UnixNano() = ns, Postgres TIMESTAMP precision 6 = µs
  • Bug pattern: an API returns µs, code divides by 1000 once expecting seconds — actually got ms; result is 1000× off

Millisecond timer, time to ms, milliseconds to seconds conversion

Quick reference for the unit phrasings: "time to ms" (any time value scaled into milliseconds), "milliseconds to seconds conversion" (÷1000), and "millisecond timer" (a high-resolution timer for short intervals). For measuring elapsed time prefer a monotonic clock — wall-clock time can jump backwards on NTP correction or DST.

  • Time to ms / time to milliseconds: seconds × 1000 = ms; microseconds ÷ 1000 = ms; nanoseconds ÷ 1,000,000 = ms
  • Milliseconds to seconds conversion: ms ÷ 1000 = seconds; Math.floor(ms/1000) for integer seconds
  • Millisecond timer (JavaScript): performance.now() returns sub-ms float since page load; Date.now() returns wall-clock ms
  • Millisecond timer (Python): time.perf_counter() (monotonic float seconds); time.monotonic_ns() returns ns
  • Millisecond timer (Java): System.nanoTime() for monotonic ns; Instant.now() for wall-clock ns precision
  • Stopwatch rule: use monotonic clocks for elapsed time; wall-clock can jump backwards on NTP or DST

FAQ

Is a 13-digit timestamp always milliseconds?
For modern real-world Unix timestamps, yes: 13 digits usually means milliseconds. Very far-future seconds timestamps can also reach 13 digits, so critical systems should still carry explicit unit metadata.
Should I store seconds or milliseconds?
Store the unit your system naturally uses, but document it and keep it consistent. JavaScript-heavy systems often use milliseconds; Unix-style backends and many databases commonly use seconds or native datetime columns.
Why use Math.floor(ms / 1000) instead of ms / 1000?
Unix seconds are usually whole seconds. Math.floor removes the fractional part so APIs expecting integer seconds do not receive a decimal value.
How do I convert milliseconds to seconds?
Divide by 1000 and drop the fraction: Math.floor(ms / 1000) in JavaScript, ms // 1000 in Python, or ms / 1000 with integer division in Go. To go the other way, multiply seconds by 1000.