Introduction
Timestamps come in various formats and precisions. Understanding these formats is crucial for developers working with time data, APIs, databases, and distributed systems.
Quick Summary: Unix timestamps (seconds, milliseconds, microseconds, nanoseconds), ISO 8601 strings, and RFC 3339 formats are the most common. Each serves different purposes in software development.
Unix Timestamp Formats
Unix Epoch (POSIX Time)
Unix timestamp represents time as number of seconds/milliseconds since January 1, 1970, 00:00:00 UTC.
TEXT1Unix Epoch Reference: 2 Start Date: January 1, 1970, 00:00:00 UTC 3 Current: January 1, 2026, 00:00:00 UTC 4 Timestamp: 1735689600 (seconds)
Precision Levels
| Precision | Example | Magnitude | Common Use |
|---|---|---|---|
| Seconds | 1735689600 | 10 digits | Unix/Linux systems |
| Milliseconds | 17356896000000 | 13 digits | JavaScript, Web APIs |
| Microseconds | 173568960000000000 | 16 digits | High-precision timing |
| Nanoseconds | 173568960000000000000 | 19 digits | Scientific computing |
Code Examples: Different Precisions
JAVASCRIPT1// JavaScript uses milliseconds by default 2const msTimestamp = Date.now(); // 17356896000000 3const secTimestamp = Math.floor(Date.now() / 1000); // 1735689600 4const nsTimestamp = Date.now() * 1000000; // 173568960000000000000 5 6console.log('Milliseconds:', msTimestamp); 7console.log('Seconds:', secTimestamp); 8console.log('Nanoseconds:', nsTimestamp);
PYTHON1from datetime import datetime 2import time 3 4# Python supports multiple precisions 5now = datetime.now(datetime.timezone.utc) 6sec_timestamp = int(now.timestamp()) 7ms_timestamp = int(now.timestamp() * 1000) 8us_timestamp = int(now.timestamp() * 1000000) 9ns_timestamp = int(now.timestamp() * 1000000000) 10 11print(f'Seconds: {sec_timestamp}') 12print(f'Milliseconds: {ms_timestamp}') 13print(f'Microseconds: {us_timestamp}') 14print(f'Nanoseconds: {ns_timestamp}')
JAVA1import java.time.Instant; 2 3// Java supports multiple precisions 4Instant now = Instant.now(); 5long secTimestamp = now.getEpochSecond(); // 1735689600 6long msTimestamp = now.toEpochMilli(); // 17356896000000 7int nsTimestamp = now.getNano(); // Nanoseconds within second 8 9System.out.println("Seconds: " + secTimestamp); 10System.out.println("Milliseconds: " + msTimestamp); 11System.out.println("Nanoseconds: " + nsTimestamp);
ISO 8601 Format
Definition
ISO 8601 is an international standard for representing dates and times. It's the most widely used format for storing and exchanging timestamps.
Format Variants
TEXT1Basic ISO 8601 Formats: 2 1. Calendar Date: 2026-01-01 3 2. Date and Time: 2026-01-01T12:00:00 4 3. With Time Zone: 2026-01-01T12:00:00+08:00 5 4. UTC (Z notation): 2026-01-01T12:00:00Z 6 5. With Fractional Seconds: 2026-01-01T12:00:00.123Z 7 6. With Milliseconds: 2026-01-01T12:00:00.123Z 8 7. With Nanoseconds: 2026-01-01T12:00:00.123456789Z
Breaking Down ISO 8601
TEXT1Format: YYYY-MM-DDThh:mm:ss.sssTZD 2 3Components: 4 YYYY - Four-digit year (2026) 5 MM - Two-digit month (01) 6 DD - Two-digit day (01) 7 T - Separator between date and time 8 hh - Two-digit hour (00-23) 9 mm - Two-digit minute (00-59) 10 ss - Two-digit second (00-59) 11 sss - Fractional seconds (optional) 12 TZD - Time zone designator (Z, +08:00, -05:00)
Code Examples: ISO 8601
JAVASCRIPT1// JavaScript has built-in ISO 8601 support 2const now = new Date(); 3const isoString = now.toISOString(); // "2026-01-01T12:00:00.000Z" 4 5// Parse ISO 8601 6const date = new Date('2026-01-01T12:00:00Z'); 7 8console.log('ISO 8601:', isoString); 9console.log('Parsed:', date.toISOString());
PYTHON1from datetime import datetime, timezone 2 3# Generate ISO 8601 4now_utc = datetime.now(timezone.utc) 5iso_string = now_utc.isoformat() # "2026-01-01T12:00:00+00:00" 6 7# Parse ISO 8601 8parsed_date = datetime.fromisoformat('2026-01-01T12:00:00+00:00') 9 10print(f'ISO 8601: {iso_string}') 11print(f'Parsed: {parsed_date.isoformat()}')
JAVA1import java.time.Instant; 2import java.time.format.DateTimeFormatter; 3 4// Generate ISO 8601 5Instant now = Instant.now(); 6String isoString = now.toString(); // "2026-01-01T12:00:00:00Z" 7 8// Parse ISO 8601 9Instant parsed = Instant.parse("2026-01-01T12:00:00:00Z"); 10 11System.out.println("ISO 8601: " + isoString); 12System.out.println("Parsed: " + parsed);
RFC 3339 Format
Definition
RFC 3339 is a subset of ISO 8601 specifically designed for internet protocols and email standards.
Differences from ISO 8601
| Feature | ISO 8601 | RFC 3339 |
|---|---|---|
| Format | Multiple variants | Fixed format |
| Time Zone | Can use offset or Z | Can use offset or Z |
| Applications | General purpose | Internet protocols (HTTP, Email) |
| Fractional Seconds | Optional | Optional |
| Example | 2026-01-01T12:00:00+08:00 | 2026-01-01T12:00:00+08:00 |
Note: RFC 3339 is almost identical to ISO 8601. In practice, they're used interchangeably for internet applications.
Code Examples: RFC 3339
JAVASCRIPT1// RFC 3339 is similar to ISO 8601 2const now = new Date(); 3const rfc3339String = now.toISOString(); // "2026-01-01T12:00:00.000Z" 4 5// RFC 3339 commonly used in HTTP headers 6const httpDate = now.toUTCString(); // "Wed, 01 Jan 2026 12:00:00 GMT" 7 8console.log('RFC 3339:', rfc3339String); 9console.log('HTTP Date:', httpDate);
PYTHON1from datetime import datetime, timezone 2import email.utils 3 4# Generate RFC 3339 (same as ISO 8601) 5now_utc = datetime.now(timezone.utc) 6rfc3339_string = now_utc.isoformat() # "2026-01-01T12:00:00+00:00" 7 8# Generate HTTP date format 9http_date = email.utils.format_datetime(now_utc) 10 11print(f'RFC 3339: {rfc3339_string}') 12print(f'HTTP Date: {http_date}')
Format Conversion
Unix Timestamp ↔ ISO 8601
JAVASCRIPT1// Unix to ISO 8601 2function unixToIso(unixTimestamp, precision = 'ms') { 3 let ts = unixTimestamp; 4 if (precision === 's') { 5 ts = unixTimestamp * 1000; 6 } else if (precision === 'us') { 7 ts = unixTimestamp / 1000; 8 } else if (precision === 'ns') { 9 ts = unixTimestamp / 1000; 10 } else if (precision === 'ns') { 11 ts = unixTimestamp / 1000000; 12 } 13 return new Date(ts).toISOString(); 14} 15 16// ISO 8601 to Unix 17function isoToUnix(isoString) { 18 return Math.floor(new Date(isoString).getTime() / 1000); 19} 20 21// Examples 22const unixTs = 1735689600; 23const isoStr = unixToIso(unixTs); // "2026-01-01T00:00:00.000Z" 24const backToUnix = isoToUnix(isoStr); // 1735689600 25 26console.log('Unix → ISO:', isoStr); 27console.log('ISO → Unix:', backToUnix);
PYTHON1from datetime import datetime, timezone 2 3def unix_to_iso(unix_timestamp, precision='s'): 4 """Convert Unix timestamp to ISO 8601 string""" 5 ts = unix_timestamp 6 if precision == 's': 7 ts = unix_timestamp 8 elif precision == 'ms': 9 ts = unix_timestamp / 1000 10 elif precision == 'us': 11 ts = unix_timestamp / 1000 12 elif precision == 'ns': 13 ts = unix_timestamp / 1000000 14 elif precision == 'ns': 15 ts = unix_timestamp / 1000000000 16 17 dt = datetime.fromtimestamp(ts, timezone.utc) 18 return dt.isoformat() 19 20def iso_to_unix(iso_string): 21 """Convert ISO 8601 string to Unix timestamp""" 22 dt = datetime.fromisoformat(iso_string) 23 return int(dt.timestamp()) 24 25# Examples 26unix_ts = 1735689600 27iso_str = unix_to_iso(unix_ts) # "2026-01-01T00:00:00+00:00" 28back_to_unix = iso_to_unix(iso_str) # 1735689600 29 30print(f'Unix → ISO: {iso_str}') 31print(f'ISO → Unix: {back_to_unix}')
Precision Detection
Detecting Unix Timestamp Precision
JAVASCRIPT1function detectPrecision(timestamp) { 2 const str = timestamp.toString(); 3 4 if (str.length === 10) { 5 return 'seconds'; 6 } else if (str.length === 13) { 7 return 'milliseconds'; 8 } else if (str.length === 16) { 9 return 'microseconds'; 10 } else if (str.length === 19) { 11 return 'nanoseconds'; 12 } 13 14 return 'unknown'; 15} 16 17// Examples 18console.log(detectPrecision(1735689600)); // "seconds" 19console.log(detectPrecision(17356896000000)); // "milliseconds" 20console.log(detectPrecision(173568960000000000)); // "microseconds" 21console.log(detectPrecision(173568960000000000000)); // "nanoseconds"
PYTHON1def detect_precision(timestamp): 2 """Detect Unix timestamp precision""" 3 str_ts = str(int(timestamp)) 4 5 if len(str_ts) == 10: 6 return 'seconds' 7 elif len(str_ts) == 13: 8 return 'milliseconds' 9 elif len(str_ts) == 16: 10 return 'microseconds' 11 elif len(str_ts) == 19: 12 return 'nanoseconds' 13 14 return 'unknown' 15 16# Examples 17print(detect_precision(1735689600)) # "seconds" 18print(detect_precision(173568960000000)) # "milliseconds" 19print(detect_precision(173568960000000000)) # "microseconds" 20print(detect_precision(173568960000000000000)) # "nanoseconds"
Comparison Table
Unix Timestamp vs ISO 8601 vs RFC 3339
| Aspect | Unix Timestamp | ISO 8601 | RFC 3339 |
|---|---|---|---|
| Format | Number (integer/float) | String | String |
| Human Readable | No | Yes | Yes |
| Time Zone Info | No (implicit UTC) | Yes (optional) | Yes (optional) |
| Precision | Configurable | Configurable | Configurable |
| Storage Size | 4-8 bytes | 20-30 bytes | 20-30 bytes |
| Database Support | Universal | Universal | Universal |
| Common Use | System timestamps | APIs, JSON, databases | HTTP, Email, APIs |
| Example | 1735689600 | 2026-01-01T12:00:00:00Z | 2026-01-01T12:00:00:00Z |
Recommendation: Use Unix timestamps for internal storage and calculations. Use ISO 8601/RFC 3339 for APIs, data exchange, and human-readable formats.
Best Practices
Storage
- Use Unix timestamps in databases for efficient storage and indexing
- Use ISO 8601 for external APIs and data exchange
- Always include time zones when displaying to users
- Document format in database schema comments
SQL1-- Best practice: Store Unix timestamp in database 2CREATE TABLE events ( 3 id INT PRIMARY KEY, 4 event_timestamp BIGINT, -- Unix timestamp in milliseconds 5 description TEXT, 6 created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() 7);
API Responses
- Use ISO 8601 for API response bodies
- Include Unix timestamp for programmatic access
- Specify time zone clearly in responses
JSON1{ 2 "event": { 3 "id": 123, 4 "timestamp": 173568960000000, 5 "iso8601": "2026-01-01T12:00:00:00Z", 6 "timezone": "UTC", 7 "human_readable": "January 1, 2026 at 12:00:00 AM UTC" 8 } 9}
Error Handling
- Validate format before parsing
- Handle leap seconds in high-precision applications
- Graceful degradation for unknown formats
JAVASCRIPT1// Validate ISO 8601 format 2function isValidISO8601(str) { 3 const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2}:\d{2})?$/; 4 return isoRegex.test(str); 5} 6 7// Handle parsing errors 8function safeParseISO8601(str) { 9 try { 10 return new Date(str); 11 } catch (error) { 12 console.error('Invalid ISO 8601 format:', str); 13 return new Date(); // Fallback to current time 14 } 15}
Common Pitfalls
Pitfall 1: Assuming Unix Timestamp is Always Seconds
JAVASCRIPT1// ❌ Wrong: Always dividing by 1000 2const timestamp = Date.now(); 3const wrongDate = new Date(timestamp / 1000); // Incorrect division 4 5// ✅ Right: Check precision first 6const date = new Date(timestamp); // Date accepts milliseconds directly
Pitfall 2: Ignoring Time Zones
JAVASCRIPT1// ❌ Wrong: Creating local time without timezone 2const localTime = new Date('2026-01-01T12:00:00'); // Ambiguous 3 4// ✅ Right: Specify timezone explicitly 5const utcTime = new Date('2026-01-01T12:00:00Z'); // Clear UTC 6const tokyoTime = new Date('2026-01-01T12:00:00+09:00'); // Tokyo time
Pitfall 3: Mixing Formats
JAVASCRIPT1// ❌ Wrong: Inconsistent formats in API 2{ 3 "timestamp": 1735689600, 4 "date": "01/01/2026", 5 "time": "12:00 PM", 6 "datetime": "2026-01-01 12:00" 7} 8 9// ✅ Right: Consistent ISO 8601 format 10{ 11 "timestamp": 1735689600, 12 "iso8601": "2026-01-01T12:00:00:00Z", 13 "timezone": "UTC" 14}
Related Tools
- Unix Timestamp Converter - Convert between Unix timestamps and dates with auto precision detection
- ISO 8601 Converter - Convert to/from ISO 8601 format
- RFC 3339 Converter - Work with RFC 3339 timestamp format
- Current Timestamp - Get current time in multiple formats and precisions
- Timestamp Validator - Validate and detect timestamp formats
FAQ
Q: What's the difference between ISO 8601 and RFC 3339?
A: RFC 3339 is a subset of ISO 8601 designed for internet protocols. They're nearly identical in practice, but RFC 3339 has stricter format rules.
Q: How do I know if a Unix timestamp is in seconds or milliseconds?
A: Count digits: 10 digits = seconds, 13 digits = milliseconds. You can also check the year (seconds = 1970+, milliseconds = 1970+).
Q: What precision should I use for my application?
A: Use milliseconds for general web applications (JavaScript default), seconds for database storage efficiency, or microseconds/nanoseconds for high-precision timing.
Q: Does ISO 8601 support time zones?
A: Yes, ISO 8601 supports time zone offsets (+08:00) and Z notation for UTC.
Q: How do I handle time zones with Unix timestamps?
A: Unix timestamps are always UTC. Convert to local time only when displaying to users using their timezone settings.
Q: What's the maximum Unix timestamp value?
A: For 64-bit systems: January 19, 2038 (year 2038 problem) is not an issue. The theoretical maximum is billions of years into the future.