How can I get seconds since epoch in JavaScript?

To get seconds since epoch in JavaScript, you can use Date.getTime() which returns milliseconds since January 1, 1970 (Unix epoch), then divide by 1000 to convert to seconds.

Syntax

var date = new Date();
var epochSeconds = Math.round(date.getTime() / 1000);

Method 1: Using Math.round()

The most common approach uses Math.round() to handle decimal precision:

var currentDate = new Date();
var epochSeconds = Math.round(currentDate.getTime() / 1000);
console.log("Seconds since epoch:", epochSeconds);
console.log("Type:", typeof epochSeconds);
Seconds since epoch: 1594821507
Type: number

Method 2: Using Math.floor()

For exact truncation without rounding:

var currentDate = new Date();
var epochSeconds = Math.floor(currentDate.getTime() / 1000);
console.log("Seconds (floor):", epochSeconds);

// Compare with milliseconds
console.log("Milliseconds:", currentDate.getTime());
Seconds (floor): 1594821507
Milliseconds: 1594821507123

Method 3: Using Date.now()

A more concise approach using Date.now():

var epochSeconds = Math.floor(Date.now() / 1000);
console.log("Current epoch seconds:", epochSeconds);

// One-liner
console.log("One-liner result:", Math.floor(Date.now() / 1000));
Current epoch seconds: 1594821507
One-liner result: 1594821507

How It Works

getTime() returns milliseconds since Unix epoch (January 1, 1970, 00:00:00 UTC). Dividing by 1000 converts milliseconds to seconds. Math.round() handles fractional seconds, while Math.floor() truncates them.

Comparison

Method Handles Decimals Performance
Math.round() Rounds to nearest Standard
Math.floor() Truncates Slightly faster
Date.now() With Math.floor() Most efficient

Conclusion

Use Math.floor(Date.now() / 1000) for the most efficient approach to get seconds since epoch. Both Math.round() and Math.floor() work well depending on whether you need rounding or truncation.

Updated on: 2026-03-15T23:18:59+05:30

434 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements