Understanding Unix Timestamps for Time Calculations
To calculate the time difference between two Unix timestamps, subtract the earlier one from the later one — the result is the elapsed time in seconds. From there, divide by 60 for minutes, 3600 for hours, or 86400 for days. This works because a Unix timestamp (also called epoch or POSIX time) is a single number: the count of seconds since January 1, 1970, 00:00:00 UTC. There is no calendar math, no time-zone offset, and no daylight-saving adjustment to worry about — just subtraction of two absolute numbers.
That's the summary an AI overview gives you. What it can't give you is the part that actually breaks in production: the two timestamps must be in the same unit (both seconds or both milliseconds), the difference is unaffected by time zones and DST because the values are absolute UTC, and the only true elapsed-time answer comes from the raw subtraction — not from subtracting local wall-clock times. This page gives you the reference tables, the per-language code, and a diagram of exactly why the arithmetic is safe.
Want to subtract two dates without writing code? Try our free Unix Timestamp Converter to convert each timestamp and verify the difference instantly. If you are working with calendar dates rather than epoch numbers, our Time Duration Calculator finds the time between two dates — including the hours, minutes, and total days between them — without any code at all.
Try it in your browser below — everything runs client-side:
Unix Epoch Time Converter
Convert Unix timestamps to dates and dates to epoch time instantly. Supports milliseconds, timezones, and multiple formats.
Open the full Unix Epoch Time Converter tool →Basic Time Difference Calculation
Simple Example:
Start time: 1704067200 (Jan 1, 2024 00:00:00 UTC)
End time: 1704153600 (Jan 2, 2024 00:00:00 UTC)
Difference: 1704153600 - 1704067200 = 86400 seconds = 1 day
The difference is always in seconds with Unix timestamps. Convert to other units as needed:
Seconds: diff = end_timestamp - start_timestamp
Minutes: diff / 60
Hours: diff / 3600
Days: diff / 86400
Time Unit Conversion Reference
Divide the seconds difference by the constant below to get any other unit. Keep this table handy — these six constants cover almost every timestamp calculation you will ever do.
| Unit | Seconds per unit | Convert seconds → unit | Exact? |
|---|---|---|---|
| Second | 1 | diff | Exact |
| Minute | 60 | diff / 60 | Exact |
| Hour | 3,600 | diff / 3600 | Exact |
| Day | 86,400 | diff / 86400 | Exact |
| Week | 604,800 | diff / 604800 | Exact |
| Month (~30 d) | 2,592,000 | diff / 2592000 | Approximate |
| Year (~365 d) | 31,536,000 | diff / 31536000 | Approximate |
Seconds through weeks are exact because those units always contain the same number of seconds. Months and years vary in length (28–31 days; 365 or 366 days), so treat them as estimates and reach for a date library when precision matters.
Subtract Two Timestamps in Any Language
The logic is identical everywhere — end - start — but the unit each platform hands you differs. This table is the "which line do I write" cheat sheet:
| Language / system | Get "now" as a timestamp | Native unit | Difference in seconds |
|---|---|---|---|
| JavaScript | Date.now() | milliseconds | (end - start) / 1000 |
| JavaScript (already seconds) | Math.floor(Date.now()/1000) | seconds | end - start |
| Python | time.time() | seconds (float) | end - start |
| PHP | time() | seconds | $end - $start |
| SQL (MySQL) | UNIX_TIMESTAMP() | seconds | end - start |
| Java | System.currentTimeMillis() | milliseconds | (end - start) / 1000 |
| Go | time.Now().Unix() | seconds | end - start |
The single row to memorize: JavaScript and Java give you milliseconds, so divide by 1000 to get seconds. Everything else is already in seconds.
Practical Examples in Different Languages
JavaScript:
const startTime = 1704067200; // Jan 1, 2024
const endTime = 1704153600; // Jan 2, 2024
const secondsDiff = endTime - startTime; // 86400
const minutesDiff = secondsDiff / 60; // 1440
const hoursDiff = secondsDiff / 3600; // 24
const daysDiff = secondsDiff / 86400; // 1
console.log(`Difference: ${daysDiff} days`);
Python:
start_time = 1704067200 # Jan 1, 2024
end_time = 1704153600 # Jan 2, 2024
seconds_diff = end_time - start_time # 86400
minutes_diff = seconds_diff / 60 # 1440
hours_diff = seconds_diff / 3600 # 24
days_diff = seconds_diff / 86400 # 1.0
print(f"Difference: {days_diff} days")
PHP:
$startTime = 1704067200; // Jan 1, 2024
$endTime = 1704153600; // Jan 2, 2024
$secondsDiff = $endTime - $startTime; // 86400
$minutesDiff = $secondsDiff / 60; // 1440
$hoursDiff = $secondsDiff / 3600; // 24
$daysDiff = $secondsDiff / 86400; // 1
echo "Difference: $daysDiff days";
SQL:
SELECT
(end_timestamp - start_timestamp) AS seconds_diff,
(end_timestamp - start_timestamp) / 60 AS minutes_diff,
(end_timestamp - start_timestamp) / 3600 AS hours_diff,
(end_timestamp - start_timestamp) / 86400 AS days_diff
FROM events
WHERE event_id = 123;
Handling Time Zones
Unix timestamps are always in UTC (Coordinated Universal Time). They're timezone-agnostic—the same Unix timestamp represents the same moment worldwide.
Example:
Timestamp: 1704067200
UTC Time: 2024-01-01 00:00:00 UTC
EST (UTC-5): 2023-12-31 19:00:00
JST (UTC+9): 2024-01-01 09:00:00
Sydney (UTC+11): 2024-01-01 11:00:00
The timestamp is identical; only the local time representation differs.
Why this makes subtraction DST-safe: Because both timestamps live on the absolute UTC timeline, a daylight-saving transition happening between your two events does not distort the result. Subtracting the raw timestamps returns the true number of elapsed seconds — no "spring forward" hour lost, no "fall back" hour double-counted. The classic off-by-one-hour bug only appears when you subtract local wall-clock times instead of timestamps. Store and compare as Unix timestamps and the problem disappears.
Converting to Local Time:
JavaScript:
const timestamp = 1704067200;
const date = new Date(timestamp * 1000); // JavaScript uses milliseconds
const utcTime = date.toUTCString();
const localTime = date.toLocaleString();
const estTime = date.toLocaleString('en-US', { timeZone: 'America/New_York' });
console.log(`UTC: ${utcTime}`);
console.log(`Local: ${localTime}`);
console.log(`EST: ${estTime}`);
Calculating Duration
From Start Time to Now:
JavaScript:
const startTime = Math.floor(Date.now() / 1000); // Current Unix timestamp
const now = Math.floor(Date.now() / 1000);
const elapsedSeconds = now - startTime;
console.log(`Elapsed: ${elapsedSeconds} seconds`);
Python:
import time
start_time = time.time() # Current Unix timestamp
# ... do something ...
now = time.time()
elapsed_seconds = now - start_time
print(f"Elapsed: {elapsed_seconds:.2f} seconds")
Milliseconds and Microseconds
Some systems use milliseconds (JavaScript, Node.js) or microseconds instead of seconds.
Converting Units:
Unix seconds: 1704067200
Unix milliseconds: 1704067200000 (seconds × 1,000)
Unix microseconds: 1704067200000000 (seconds × 1,000,000)
JavaScript (Uses Milliseconds):
// Current timestamp in milliseconds
const now = Date.now(); // e.g., 1704153600000
// Convert to seconds
const seconds = Math.floor(now / 1000); // 1704153600
// Convert seconds back to milliseconds
const ms = seconds * 1000;
Python (Uses Seconds):
import time
# Current timestamp in seconds
now = time.time() # e.g., 1704153600.123
# Current timestamp in milliseconds
now_ms = int(time.time() * 1000) # 1704153600123
Formatted Duration Output
Converting a difference into human-readable format:
JavaScript:
function formatDuration(seconds) {
const units = [
{ name: 'year', seconds: 31536000 },
{ name: 'month', seconds: 2592000 },
{ name: 'day', seconds: 86400 },
{ name: 'hour', seconds: 3600 },
{ name: 'minute', seconds: 60 },
{ name: 'second', seconds: 1 }
];
const parts = [];
let remaining = Math.floor(seconds);
for (const unit of units) {
const count = Math.floor(remaining / unit.seconds);
if (count > 0) {
parts.push(`${count} ${unit.name}${count > 1 ? 's' : ''}`);
remaining -= count * unit.seconds;
}
}
return parts.join(', ');
}
console.log(formatDuration(90061)); // "1 day, 1 hour, 1 minute, 1 second"
Python:
def format_duration(seconds):
units = [
('year', 31536000),
('month', 2592000),
('day', 86400),
('hour', 3600),
('minute', 60),
('second', 1)
]
parts = []
remaining = int(seconds)
for unit_name, unit_seconds in units:
count = remaining // unit_seconds
if count > 0:
plural = 's' if count > 1 else ''
parts.append(f"{count} {unit_name}{plural}")
remaining -= count * unit_seconds
return ', '.join(parts)
print(format_duration(90061)) # "1 day, 1 hour, 1 minute, 1 second"
Age Calculation
Calculating Someone's Age:
function calculateAge(birthTimestamp) {
const now = Math.floor(Date.now() / 1000);
const ageSeconds = now - birthTimestamp;
const ageYears = ageSeconds / 31536000;
return Math.floor(ageYears);
}
const birthDate = new Date('1990-01-15').getTime() / 1000;
console.log(`Age: ${calculateAge(birthDate)}`);
Expired vs Valid Timestamps
Checking if Something is Expired:
JavaScript:
const expirationTime = 1706745600; // Expiration timestamp
const now = Math.floor(Date.now() / 1000);
if (now > expirationTime) {
console.log("Expired");
} else {
const secondsUntilExpiry = expirationTime - now;
const daysUntilExpiry = secondsUntilExpiry / 86400;
console.log(`Expires in ${daysUntilExpiry.toFixed(1)} days`);
}
Working with Intervals
Scheduling at Regular Intervals:
JavaScript:
const startTime = Math.floor(Date.now() / 1000);
const intervalSeconds = 3600; // Every hour
setInterval(() => {
const now = Math.floor(Date.now() / 1000);
const elapsedIntervals = Math.floor((now - startTime) / intervalSeconds);
console.log(`Interval ${elapsedIntervals} occurred`);
}, intervalSeconds * 1000);
Database Queries for Time Differences
SQL Examples:
-- Events happened within the last 24 hours
SELECT * FROM events
WHERE timestamp > UNIX_TIMESTAMP() - 86400;
-- Events that lasted more than 1 hour
SELECT id, end_timestamp - start_timestamp AS duration_seconds
FROM events
WHERE (end_timestamp - start_timestamp) > 3600;
-- Group by duration ranges
SELECT
CASE
WHEN duration < 60 THEN 'less than 1 minute'
WHEN duration < 3600 THEN 'less than 1 hour'
WHEN duration < 86400 THEN 'less than 1 day'
ELSE 'more than 1 day'
END AS duration_range,
COUNT(*) AS count
FROM (
SELECT (end_timestamp - start_timestamp) AS duration
FROM events
) subquery
GROUP BY duration_range;
Common Mistakes
Forgetting JavaScript Uses Milliseconds:
// Wrong
const timestamp = 1704067200;
const date = new Date(timestamp); // Interprets as milliseconds!
// Gives date in 1970 (55 years ago)
// Correct
const date = new Date(timestamp * 1000);
Not Accounting for Leap Seconds: Unix timestamps assume no leap seconds exist (they're skipped), which can cause issues in precise systems.
Month/Year Approximations:
Months are NOT consistent length
A "month" varies: 28-31 days
Use date libraries for precise month/year math
Using Unix Timestamp Converter Tool
The Unix Timestamp Converter helps:
- Convert human-readable dates to timestamps
- Convert timestamps to human-readable format
- Calculate differences between dates
- Verify timestamp values
Use it to validate your calculations before implementing in code.
Conclusion: Simple Subtraction for Time Differences
Calculating time differences with Unix timestamps is simple: subtract one from the other. The result is in seconds; convert as needed. The beauty of Unix timestamps is their timezone-independence and simplicity—they work identically across all programming languages and systems. Understanding timestamp arithmetic is fundamental for any developer working with dates, scheduling, logging, or time-based operations.