Programming•9 min read
Unix Timestamps: Complete Guide for Developers
Master Unix timestamps - conversion, formatting, time zones, and best practices for handling time in applications.
By Andy Pham
Unix Timestamps: Complete Guide for Developers
Unix timestamps are the foundation of time handling in programming. This guide covers everything from basics to advanced usage.
What is a Unix Timestamp?
A Unix timestamp is the number of seconds elapsed since January 1, 1970, 00:00:00 UTC (the Unix Epoch).
Current timestamp: 1704067200
Represents: January 1, 2024 00:00:00 UTC
Getting Current Timestamp
JavaScript
// Seconds
const timestamp = Math.floor(Date.now() / 1000);
// Milliseconds
const timestampMs = Date.now();
// From Date object
const date = new Date();
const ts = Math.floor(date.getTime() / 1000);
Python
import time
from datetime import datetime
# Current timestamp
timestamp = int(time.time())
# Using datetime
timestamp = int(datetime.now().timestamp())
PHP
// Current timestamp
$timestamp = time();
// From DateTime
$dt = new DateTime();
$timestamp = $dt->getTimestamp();
Java
// Seconds
long timestamp = System.currentTimeMillis() / 1000;
// Using Instant
import java.time.Instant;
long ts = Instant.now().getEpochSecond();
Converting Timestamps
Timestamp to Date
// JavaScript
const timestamp = 1704067200;
const date = new Date(timestamp * 1000);
console.log(date.toISOString()); // 2024-01-01T00:00:00.000Z
// Format options
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
};
console.log(date.toLocaleDateString('en-US', options));
# Python
from datetime import datetime
timestamp = 1704067200
dt = datetime.fromtimestamp(timestamp)
print(dt.strftime('%Y-%m-%d %H:%M:%S'))
# UTC
dt_utc = datetime.utcfromtimestamp(timestamp)
Date to Timestamp
// JavaScript
const date = new Date('2024-01-01T00:00:00Z');
const timestamp = Math.floor(date.getTime() / 1000);
// Parse specific format
function parseDate(dateStr, format) {
const [y, m, d] = dateStr.split('-');
return Math.floor(new Date(y, m - 1, d).getTime() / 1000);
}
Time Zones
Working with Time Zones
// Convert to specific timezone
function toTimezone(timestamp, timezone) {
const date = new Date(timestamp * 1000);
return date.toLocaleString('en-US', { timeZone: timezone });
}
console.log(toTimezone(1704067200, 'America/New_York'));
console.log(toTimezone(1704067200, 'Asia/Tokyo'));
console.log(toTimezone(1704067200, 'Europe/London'));
Common Time Zone Offsets
| Time Zone | Offset | Example City |
|---|---|---|
| UTC | +0:00 | London (winter) |
| EST | -5:00 | New York |
| PST | -8:00 | Los Angeles |
| JST | +9:00 | Tokyo |
| AEST | +10:00 | Sydney |
Timestamp Formats
Seconds vs Milliseconds
// Seconds (10 digits)
const seconds = 1704067200;
// Milliseconds (13 digits)
const milliseconds = 1704067200000;
// Microseconds (16 digits)
const microseconds = 1704067200000000;
// Detection and conversion
function normalizeTimestamp(ts) {
const str = ts.toString();
if (str.length === 10) return ts * 1000;
if (str.length === 13) return ts;
if (str.length === 16) return Math.floor(ts / 1000);
throw new Error('Unknown timestamp format');
}
Common Operations
Add/Subtract Time
const timestamp = Math.floor(Date.now() / 1000);
// Add 1 hour
const plusHour = timestamp + 3600;
// Add 1 day
const plusDay = timestamp + 86400;
// Add 1 week
const plusWeek = timestamp + 604800;
// Subtract 30 days
const minus30Days = timestamp - (30 * 86400);
Calculate Difference
function timeDifference(ts1, ts2) {
const diff = Math.abs(ts2 - ts1);
return {
seconds: diff,
minutes: Math.floor(diff / 60),
hours: Math.floor(diff / 3600),
days: Math.floor(diff / 86400)
};
}
Relative Time
function timeAgo(timestamp) {
const now = Math.floor(Date.now() / 1000);
const diff = now - timestamp;
if (diff < 60) return 'just now';
if (diff < 3600) return `${Math.floor(diff / 60)} minutes ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)} hours ago`;
if (diff < 2592000) return `${Math.floor(diff / 86400)} days ago`;
if (diff < 31536000) return `${Math.floor(diff / 2592000)} months ago`;
return `${Math.floor(diff / 31536000)} years ago`;
}
The Year 2038 Problem
Unix timestamps stored as 32-bit signed integers will overflow on:
January 19, 2038 at 03:14:07 UTC
Solution
// Use 64-bit integers or BigInt
const timestamp = BigInt(Date.now());
// Or use ISO 8601 strings for storage
const isoString = new Date().toISOString();
Best Practices
- Always store in UTC
// Good
const utcTimestamp = Math.floor(Date.now() / 1000);
// Bad - includes timezone offset
const localTime = new Date().toString();
- Use milliseconds for precision
// High-precision operations
const preciseTimestamp = Date.now();
- Validate timestamps
function isValidTimestamp(ts) {
const num = Number(ts);
return !isNaN(num) && num > 0 && num < 2147483647000;
}
- Use libraries for complex operations
// date-fns
import { fromUnixTime, format } from 'date-fns';
const date = fromUnixTime(1704067200);
console.log(format(date, 'yyyy-MM-dd HH:mm:ss'));
Try Our Tools
- Timestamp Converter - Convert timestamps
- Date Calculator - Calculate date differences
- Time Converter - Convert time units
Conclusion
Unix timestamps are essential for handling time in applications. Use UTC, be aware of precision requirements, and leverage libraries for complex date operations.