Understanding Unix Timestamps for Time Calculations
Unix timestamps (also called epoch time or POSIX time) represent a specific moment as a single number: seconds since January 1, 1970, 00:00:00 UTC. This simple representation makes calculating time differences straightforward—it's just subtraction.
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 Conversions
Seconds to Other Units:
1 minute = 60 seconds
1 hour = 3,600 seconds
1 day = 86,400 seconds
1 week = 604,800 seconds
1 month ≈ 2,592,000 seconds (30 days)
1 year ≈ 31,536,000 seconds (365 days)
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.
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.

