Guide / code

Get the current Unix timestamp in code

Practical examples for retrieving Unix seconds or milliseconds in JavaScript, Python, Java, PHP, Go, SQL and Shell.

JavaScript

const milliseconds = Date.now()
const seconds = Math.floor(milliseconds / 1000)

Python

import time
seconds = int(time.time())
milliseconds = time.time_ns() // 1_000_000

Java

long milliseconds = System.currentTimeMillis();
long seconds = java.time.Instant.now().getEpochSecond();

PHP, Go, SQL and Shell

PHP:   time()
Go:    time.Now().Unix()
PostgreSQL: floor(extract(epoch from now()))
Shell: date +%s

Check whether the receiving system expects seconds or milliseconds. The unit mismatch is more common than a wrong clock.

Verify the unit before using a snippet

JavaScript Date.now() returns milliseconds. Python time.time() returns seconds with a fractional part; time.time_ns() returns integer nanoseconds. Java's Instant separates whole epoch seconds from a nanosecond adjustment. Do not append zeros to a lower-resolution reading and describe it as newly measured precision.

Use the fixed fixture 1700000000 seconds, or 1700000000000 milliseconds, in a unit test. Both should produce 2023-11-14T22:13:20Z in the timestamp converter. Fixed fixtures make an off-by-1,000 error easier to identify than a changing current-time value.

JavaScript date and monotonic time

const milliseconds = Date.now()
const seconds = Math.floor(milliseconds / 1000)
const isoUtc = new Date(milliseconds).toISOString()

const started = performance.now()
// Run the operation you want to measure.
const elapsedMilliseconds = performance.now() - started

The first three expressions refer to calendar time. The last two measure a duration with a monotonic clock and are not Unix timestamps. A system clock correction can change Date.now(), whereas an elapsed-duration timer has a different purpose.

Transport large integers safely

A 19-digit nanosecond value should not be converted to a JavaScript Number before parsing. Carry it as a decimal string in JSON when the receiving environment cannot preserve large integers. Convert the string to BigInt where supported. A JSON number may already have lost its final digits before your converter receives it.

For SQL, check the database engine and session time-zone setting. Functions with similar names can return different types or apply a session zone. Store the unit contract in the schema or API documentation and verify a known fixture after every import. See ISO and Unix time for interchange format choices.

Standards and runtime references

Tools / 01—06

More timestamp tools

Each route starts with a specific input and gives a specific answer.