Timestamp Conversion Methods Across Programming Languages
Compare timestamp conversion methods across different programming languages and frameworks.
Understanding Unix Timestamps
A Unix timestamp (also known as POSIX time or Epoch time) represents the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC. This standardized time format is widely used across programming languages, databases, and system operations.
Why Use Unix Timestamps?
- Timezone Independence: Same timestamp represents same moment globally
- Simple Arithmetic: Easy to calculate time differences
- Compact Storage: Single integer instead of complex date structures
- Universal Standard: Supported by virtually all systems
- Sortable: Natural chronological ordering
Timestamp Conversion by Language
JavaScript / TypeScript
// Get current timestamp (milliseconds)
const timestamp = Date.now();
// Or in seconds
const timestampSeconds = Math.floor(Date.now() / 1000);
// Convert timestamp to Date
const date = new Date(timestamp);
// Convert Date to timestamp
const timestamp = date.getTime();
// Format date
const formatted = date.toLocaleString();
const iso = date.toISOString();
// Parse date string
const date = new Date('2024-01-15T10:30:00Z');Python
import time
from datetime import datetime
# Get current timestamp
timestamp = time.time() # Returns float with microseconds
# Convert timestamp to datetime
dt = datetime.fromtimestamp(timestamp)
# Convert datetime to timestamp
timestamp = dt.timestamp()
# Format datetime
formatted = dt.strftime('%Y-%m-%d %H:%M:%S')
# Parse date string
dt = datetime.strptime('2024-01-15 10:30:00', '%Y-%m-%d %H:%M:%S')
# UTC handling
dt_utc = datetime.utcfromtimestamp(timestamp)PHP
// Get current timestamp
$timestamp = time();
// Convert timestamp to date
$date = date('Y-m-d H:i:s', $timestamp);
// Convert date to timestamp
$timestamp = strtotime('2024-01-15 10:30:00');
// DateTime object
$dt = new DateTime();
$timestamp = $dt->getTimestamp();
// Format DateTime
$formatted = $dt->format('Y-m-d H:i:s');
// Parse date string
$dt = DateTime::createFromFormat('Y-m-d H:i:s', '2024-01-15 10:30:00');Java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
// Get current timestamp (seconds)
long timestamp = Instant.now().getEpochSecond();
// Convert timestamp to LocalDateTime
LocalDateTime dateTime = LocalDateTime.ofInstant(
Instant.ofEpochSecond(timestamp),
ZoneId.systemDefault()
);
// Convert LocalDateTime to timestamp
long timestamp = dateTime.atZone(ZoneId.systemDefault())
.toEpochSecond();
// Format date
String formatted = dateTime.format(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
);Go
import "time"
// Get current timestamp
timestamp := time.Now().Unix()
// Convert timestamp to Time
t := time.Unix(timestamp, 0)
// Format time
formatted := t.Format("2006-01-02 15:04:05")
// Parse time string
t, err := time.Parse("2006-01-02 15:04:05", "2024-01-15 10:30:00")
// UTC handling
utc := time.Now().UTC()Handling Timezones
Best Practices
- Store in UTC: Always store timestamps in UTC in databases
- Convert for Display: Convert to local timezone only for display
- Be Explicit: Always specify timezone when parsing date strings
- Handle DST: Account for daylight saving time transitions
- Use Libraries: Leverage timezone libraries (moment-timezone, date-fns-tz)
Common Timezone Pitfalls
- Assuming all days have 24 hours (DST changes)
- Not handling timezone offsets correctly
- Mixing local and UTC times
- Ignoring leap seconds in critical applications
Milliseconds vs Seconds
Different systems use different precision:
- JavaScript: Milliseconds (13 digits)
- Unix/Linux: Seconds (10 digits)
- Python: Seconds with decimal (float)
- Java: Milliseconds (System.currentTimeMillis())
Converting Between Precisions
// Seconds to milliseconds
const milliseconds = seconds * 1000;
// Milliseconds to seconds
const seconds = Math.floor(milliseconds / 1000);
// Check if timestamp is in seconds or milliseconds
const isMilliseconds = timestamp.toString().length === 13;
const isSeconds = timestamp.toString().length === 10;Common Use Cases
1. API Timestamps
APIs commonly use Unix timestamps for consistency across different clients and timezones.
2. Database Storage
Store timestamps as integers for efficient indexing and querying.
3. Log Files
Use timestamps to track when events occurred for debugging and analysis.
4. Cache Expiration
Calculate cache expiration times using timestamp arithmetic.
Best Practices Summary
- Always store timestamps in UTC
- Use appropriate precision (seconds vs milliseconds)
- Validate timestamp ranges
- Handle timezone conversions explicitly
- Consider DST transitions
- Use ISO 8601 format for human-readable dates
- Test with edge cases (leap years, DST changes)
- Document timezone assumptions
Try Our Timestamp Converter
Convert between Unix timestamps and human-readable dates: