DevToolBoxGRATIS
Blogg

Unix Timestamp Converter Online Guide: Konvertera Epoch-tid i JS, Python och SQL

14 min lasningby DevToolBox

TL;DR

A Unix timestamp is the number of seconds elapsed since January 1, 1970 00:00:00 UTC (the Unix epoch). It is a universal, timezone-independent way to represent a point in time. In JavaScript use Date.now() (milliseconds) or Math.floor(Date.now() / 1000) (seconds). In Python use time.time() or datetime.now().timestamp(). Watch out for millisecond vs second confusion, the Y2K38 overflow on 32-bit systems, and always store timestamps in UTC. Use our free Unix Timestamp Converter to instantly convert between timestamps and human-readable dates.

Key Takeaways

  • Unix timestamps count seconds (or milliseconds) since 1970-01-01T00:00:00Z, providing a timezone-neutral time representation.
  • JavaScript uses millisecond timestamps natively (Date.now()), while most Unix tools and databases use seconds.
  • Python provides time.time() for a float timestamp in seconds and datetime.fromtimestamp() for conversion back to dates.
  • The Y2K38 problem will cause 32-bit signed integer timestamps to overflow on January 19, 2038. Use 64-bit integers for future-proof storage.
  • Always store timestamps in UTC and convert to local time only at the presentation layer to avoid daylight-saving and timezone bugs.
  • ISO 8601 (2026-02-27T12:00:00Z) is the standard human-readable format that pairs well with Unix timestamps.
  • APIs should document whether timestamps are in seconds or milliseconds, and prefer ISO 8601 strings for JSON responses.

What Is a Unix Timestamp?

A Unix timestamp (also called Epoch time, POSIX time, or Unix time) is a system for tracking time as a single integer: the total number of seconds that have elapsed since the Unix epoch — January 1, 1970, at 00:00:00 Coordinated Universal Time (UTC). This moment in time was chosen as the starting point for the Unix operating system and has since become the de facto standard for time representation across virtually all programming languages, databases, and operating systems.

For example, the timestamp 1709049600 represents February 27, 2024, 12:00:00 PM UTC. Every second that passes increments this counter by one. The Unix timestamp does not account for leap seconds (a deliberate design decision), making arithmetic on timestamps straightforward: the difference between two timestamps is the number of elapsed seconds.

Need to quickly convert a timestamp? Try our free Unix Timestamp Converter tool for instant conversions between timestamps and human-readable dates.

Why Developers Use Unix Timestamps

Unix timestamps are popular for several practical reasons:

  • Timezone independence: A Unix timestamp is always UTC. There is no ambiguity about which timezone a value refers to, unlike strings like "2026-02-27 3:00 PM" which could mean different moments depending on the timezone.
  • Compact storage: A single 32-bit or 64-bit integer is far smaller than a date string like "2026-02-27T15:00:00+05:30".
  • Easy arithmetic: Adding 86400 to a timestamp gives you exactly one day later. Subtracting two timestamps gives the duration in seconds. No need to worry about month lengths or leap years.
  • Universal support: Every major programming language, database, and operating system supports Unix timestamps natively.
  • Sorting: Numeric timestamps sort naturally — you can use a simple integer comparison to order events chronologically.

Millisecond vs Second Timestamps

One of the most common sources of confusion (and bugs) is the difference between second-precision and millisecond-precision timestamps.

FormatDigitsExample (2026-02-27)Used By
Seconds10 digits1772150400Unix, PHP, Python, C, MySQL, PostgreSQL
Milliseconds13 digits1772150400000JavaScript, Java, Dart, Elasticsearch
Microseconds16 digits1772150400000000PostgreSQL (interval), Go (time.UnixMicro)
Nanoseconds19 digits1772150400000000000Go (time.UnixNano), InfluxDB

A quick way to tell them apart: if the number has 10 digits, it is in seconds. If it has 13 digits, it is in milliseconds. If you accidentally treat a millisecond timestamp as seconds (or vice versa), you will get dates that are either in the distant future (year 50,000+) or clustered around January 1970. This is by far the most common timestamp debugging issue.

Converting Timestamps in JavaScript

JavaScript is one of the most timestamp-heavy languages because the built-in Date object works with millisecond timestamps internally. Here are the essential patterns:

Getting the Current Timestamp

// Current timestamp in milliseconds
const msTimestamp = Date.now();
console.log(msTimestamp); // 1772150400000

// Current timestamp in seconds (Unix standard)
const unixTimestamp = Math.floor(Date.now() / 1000);
console.log(unixTimestamp); // 1772150400

// Using Date object
const now = new Date();
console.log(now.getTime()); // 1772150400000 (ms)

Converting a Timestamp to a Date

// From seconds to Date
const timestamp = 1772150400;
const date = new Date(timestamp * 1000); // multiply by 1000!
console.log(date.toISOString());
// "2026-02-27T00:00:00.000Z"

// From milliseconds to Date (no multiplication needed)
const msTimestamp = 1772150400000;
const date2 = new Date(msTimestamp);
console.log(date2.toISOString());
// "2026-02-27T00:00:00.000Z"

// Common mistake: forgetting to multiply
const wrong = new Date(1772150400);
console.log(wrong.toISOString());
// "1970-01-21T12:15:50.400Z" -- January 1970!

Converting a Date to a Timestamp

// Date string to timestamp
const date = new Date("2026-02-27T12:00:00Z");
const seconds = Math.floor(date.getTime() / 1000);
console.log(seconds); // 1772193600

// Parse a date with timezone offset
const localDate = new Date("2026-02-27T12:00:00+08:00");
const utcSeconds = Math.floor(localDate.getTime() / 1000);
console.log(utcSeconds); // 1772164800

Formatting Timestamps

const date = new Date(1772150400 * 1000);

// ISO 8601 (UTC)
console.log(date.toISOString());
// "2026-02-27T00:00:00.000Z"

// Locale-aware string
console.log(date.toLocaleString('en-US', { timeZone: 'America/New_York' }));
// "2/26/2026, 7:00:00 PM"

// Intl.DateTimeFormat for full control
const fmt = new Intl.DateTimeFormat('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: '2-digit',
  minute: '2-digit',
  timeZone: 'Europe/London',
  timeZoneName: 'short',
});
console.log(fmt.format(date));
// "February 27, 2026, 12:00 AM GMT"

For quick conversions during development, use our online timestamp converter to avoid manual math.

Converting Timestamps in Python

Python provides two primary modules for timestamp operations: time (low-level) and datetime (high-level).

Getting the Current Timestamp

import time
from datetime import datetime, timezone

# Current timestamp in seconds (float)
ts = time.time()
print(ts)  # 1772150400.123456

# Integer seconds
ts_int = int(time.time())
print(ts_int)  # 1772150400

# Using datetime
ts_dt = datetime.now(timezone.utc).timestamp()
print(ts_dt)  # 1772150400.123456

Converting Between Timestamps and Dates

from datetime import datetime, timezone

# Timestamp to datetime (UTC)
ts = 1772150400
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
print(dt)  # 2026-02-27 00:00:00+00:00

# Timestamp to datetime (local timezone)
dt_local = datetime.fromtimestamp(ts)
print(dt_local)  # Depends on system timezone

# Datetime to timestamp
dt = datetime(2026, 2, 27, 12, 0, 0, tzinfo=timezone.utc)
ts = dt.timestamp()
print(int(ts))  # 1772193600

# ISO 8601 format
print(dt.isoformat())  # "2026-02-27T12:00:00+00:00"

# Parse ISO 8601 string
parsed = datetime.fromisoformat("2026-02-27T12:00:00+00:00")
print(int(parsed.timestamp()))  # 1772193600

Working with Millisecond Timestamps in Python

from datetime import datetime, timezone

# JavaScript-style millisecond timestamp
ms_ts = 1772150400000

# Convert to datetime
dt = datetime.fromtimestamp(ms_ts / 1000, tz=timezone.utc)
print(dt)  # 2026-02-27 00:00:00+00:00

# Convert datetime to millisecond timestamp
ms = int(dt.timestamp() * 1000)
print(ms)  # 1772150400000

Converting Timestamps in SQL

Databases have their own timestamp types and conversion functions. Here are the most common patterns for PostgreSQL and MySQL.

PostgreSQL

-- Current Unix timestamp (seconds)
SELECT EXTRACT(EPOCH FROM NOW())::bigint;
-- 1772150400

-- Unix timestamp to timestamp with timezone
SELECT TO_TIMESTAMP(1772150400);
-- 2026-02-27 00:00:00+00

-- Timestamp to Unix timestamp
SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE
  '2026-02-27T12:00:00Z')::bigint;
-- 1772193600

-- Date arithmetic with timestamps
SELECT TO_TIMESTAMP(1772150400) + INTERVAL '7 days';
-- 2026-03-06 00:00:00+00

-- Store as bigint for millisecond precision
CREATE TABLE events (
  id SERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  created_at_ms BIGINT DEFAULT
    (EXTRACT(EPOCH FROM NOW()) * 1000)::bigint
);

MySQL

-- Current Unix timestamp (seconds)
SELECT UNIX_TIMESTAMP();
-- 1772150400

-- Unix timestamp to datetime
SELECT FROM_UNIXTIME(1772150400);
-- '2026-02-27 00:00:00'

-- Datetime to Unix timestamp
SELECT UNIX_TIMESTAMP('2026-02-27 12:00:00');
-- 1772193600

-- With timezone conversion
SELECT CONVERT_TZ(
  FROM_UNIXTIME(1772150400),
  '+00:00',
  'America/New_York'
);
-- '2026-02-26 19:00:00'

-- TIMESTAMP column (auto-converts to UTC)
CREATE TABLE logs (
  id INT AUTO_INCREMENT PRIMARY KEY,
  message TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Timezone Handling Best Practices

Timezones are the number one source of date-related bugs. Here are the rules every developer should follow:

The Golden Rule: Store UTC, Display Local

Always store timestamps in UTC (either as Unix timestamps or as TIMESTAMP WITH TIME ZONE in your database). Convert to the user's local timezone only when displaying the value in the UI. This eliminates an entire class of bugs related to daylight saving time transitions, server migrations across regions, and user relocation.

// Backend: always work in UTC
const createdAt = Math.floor(Date.now() / 1000); // UTC seconds
// Store in database as integer or TIMESTAMPTZ

// Frontend: convert to user's local timezone for display
const date = new Date(createdAt * 1000);
const localString = date.toLocaleString('en-US', {
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
});

Common Timezone Pitfalls

  • DST transitions: On the day clocks spring forward, 2:00 AM to 3:00 AM does not exist. On the day clocks fall back, 1:00 AM to 2:00 AM occurs twice. If you store local times instead of UTC, these transitions cause duplicate or missing events.
  • Server timezone: Never assume your server is in a specific timezone. A cloud migration or container restart could change the system timezone. Always set TZ=UTC in your server environment or application config.
  • Date-only values: If you only need a date (no time component), be aware that new Date("2026-02-27") in JavaScript is interpreted as midnight UTC, which might display as February 26 in western hemispheres. Always specify the time component to avoid this ambiguity.
  • Offset vs. timezone name: +05:30 is a fixed offset. Asia/Kolkata is a timezone name that correctly handles historical changes and DST rules. Always prefer IANA timezone names (like America/New_York) over fixed offsets.

Using dayjs for Timezone Conversions

import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';

dayjs.extend(utc);
dayjs.extend(timezone);

// Parse a UTC timestamp
const ts = 1772150400;
const d = dayjs.unix(ts).utc();
console.log(d.format()); // "2026-02-27T00:00:00Z"

// Convert to a specific timezone
const tokyo = d.tz('Asia/Tokyo');
console.log(tokyo.format('YYYY-MM-DD HH:mm:ss z'));
// "2026-02-27 09:00:00 JST"

// Convert from local timezone to UTC timestamp
const local = dayjs.tz('2026-02-27 15:00:00', 'America/Los_Angeles');
console.log(local.unix()); // Unix timestamp in seconds

ISO 8601 Format

ISO 8601 is the international standard for date and time representation. It is the recommended format for APIs, log files, and any human-readable date string that needs to be unambiguous.

FormatExampleNotes
Date only2026-02-27YYYY-MM-DD
UTC datetime2026-02-27T12:00:00ZZ suffix means UTC
With offset2026-02-27T12:00:00+05:30India Standard Time offset
With milliseconds2026-02-27T12:00:00.123ZSub-second precision
Week date2026-W09-5Year-Week-DayOfWeek
DurationP1Y2M3DT4H5M6S1 year 2 months 3 days 4h 5m 6s

The relationship between Unix timestamps and ISO 8601 is straightforward: a Unix timestamp represents a single moment in time, and the ISO 8601 string is the human-readable representation of that moment. Converting between them:

// JavaScript
const ts = 1772150400;
const iso = new Date(ts * 1000).toISOString();
// "2026-02-27T00:00:00.000Z"

const backToTs = Math.floor(new Date(iso).getTime() / 1000);
// 1772150400

Timestamps in APIs (REST and GraphQL)

How you represent timestamps in your API has a major impact on developer experience and bug frequency. Here are the common approaches:

Option 1: Unix Timestamps (Integer)

{
  "id": "evt_abc123",
  "created_at": 1772150400,
  "updated_at": 1772193600
}

Pros: Compact, unambiguous, easy to sort and compare, no timezone confusion. Cons: Not human-readable in API responses, requires client-side conversion, second vs millisecond ambiguity.

Option 2: ISO 8601 Strings

{
  "id": "evt_abc123",
  "created_at": "2026-02-27T00:00:00Z",
  "updated_at": "2026-02-27T12:00:00Z"
}

Pros: Human-readable, self-documenting, includes timezone information, widely supported by JSON parsers. Cons: Slightly larger payload, requires parsing for comparisons.

Option 3: Both (Recommended for Large APIs)

{
  "id": "evt_abc123",
  "created_at": "2026-02-27T00:00:00Z",
  "created_at_unix": 1772150400,
  "updated_at": "2026-02-27T12:00:00Z",
  "updated_at_unix": 1772193600
}

GraphQL Custom Scalar

# Schema definition
scalar DateTime  # ISO 8601 string
scalar Timestamp # Unix seconds integer

type Event {
  id: ID!
  name: String!
  createdAt: DateTime!
  startTime: Timestamp!
}

# Query
{
  event(id: "evt_abc123") {
    name
    createdAt  # "2026-02-27T00:00:00Z"
    startTime  # 1772150400
  }
}

Whichever format you choose, document it clearly in your API specification. Stripe uses seconds, Twitter used seconds, Slack uses seconds with a decimal portion for sub-second precision, and most modern APIs are moving toward ISO 8601 strings. The key is consistency within your API.

The Y2K38 Problem (Year 2038 Bug)

The Year 2038 problem (also known as Y2K38, the Epochalypse, or the Unix Millennium Bug) is a critical limitation of 32-bit systems that store Unix timestamps as signed 32-bit integers. The maximum value of a signed 32-bit integer is 2,147,483,647, which corresponds to:

// The last moment a 32-bit signed integer can represent
// Tuesday, January 19, 2038 at 03:14:07 UTC
const maxInt32 = 2147483647;
console.log(new Date(maxInt32 * 1000).toISOString());
// "2038-01-19T03:14:07.000Z"

// One second later, the integer overflows to -2147483648
// which maps to December 13, 1901
const overflow = -2147483648;
console.log(new Date(overflow * 1000).toISOString());
// "1901-12-13T20:45:52.000Z"

After 03:14:07 UTC on January 19, 2038, a 32-bit signed timestamp wraps around to a negative number, causing the date to jump back to 1901. This will affect:

  • Embedded systems: IoT devices, industrial controllers, and network equipment with 32-bit processors.
  • Legacy databases: MySQL TIMESTAMP columns are limited to 2038-01-19 03:14:07 UTC (use DATETIME or BIGINT instead).
  • C programs: Code using time_t as a 32-bit type (most modern 64-bit systems already use 64-bit time_t).
  • File formats: ZIP, ext3 filesystem timestamps, and other formats with 32-bit time fields.

How to Protect Your Code

Language / SystemAction
JavaScriptAlready safe. Date uses 64-bit floating point internally.
PythonAlready safe. Python integers have arbitrary precision.
C / C++Compile on 64-bit platform or use int64_t instead of time_t on 32-bit.
MySQLUse DATETIME (range to 9999-12-31) or BIGINT instead of TIMESTAMP.
PostgreSQLAlready safe. Uses 64-bit integer microseconds internally.
GoAlready safe. time.Time uses 64-bit wall clock and monotonic clock.

Common Debugging: Why Is My Date Showing 1970?

If you are seeing dates near January 1, 1970, you are almost certainly making one of these mistakes:

Mistake 1: Treating a Second Timestamp as Milliseconds

// BUG: passing seconds where milliseconds are expected
const ts = 1772150400; // seconds
const date = new Date(ts); // JavaScript expects milliseconds!
console.log(date.toISOString());
// "1970-01-21T12:15:50.400Z" -- WRONG!

// FIX: multiply by 1000
const dateFixed = new Date(ts * 1000);
console.log(dateFixed.toISOString());
// "2026-02-27T00:00:00.000Z" -- CORRECT

Mistake 2: Null or Zero Timestamp

// A timestamp of 0 = the Unix epoch itself
const date = new Date(0);
console.log(date.toISOString());
// "1970-01-01T00:00:00.000Z"

// This often happens when:
// - A database column has a default of 0
// - An API returns null/undefined and you don't check
// - A string is parsed as NaN, which becomes 0

// FIX: always validate before converting
function safeTimestampToDate(ts) {
  if (!ts || ts <= 0) return null;
  // Auto-detect seconds vs milliseconds
  const ms = ts > 1e12 ? ts : ts * 1000;
  return new Date(ms);
}

Mistake 3: String Parsing Fails Silently

// Some date strings parse to NaN/Invalid Date
const date = new Date("27/02/2026"); // DD/MM/YYYY is ambiguous
console.log(date.getTime()); // NaN in most engines

// FIX: always use ISO 8601 format
const dateFixed = new Date("2026-02-27");
console.log(dateFixed.toISOString());
// "2026-02-27T00:00:00.000Z"

Mistake 4: Timezone Offset Double-Applied

// Suppose you have a UTC timestamp
const utcTs = 1772150400;

// BUG: converting to local then treating as UTC
const localDate = new Date(utcTs * 1000);
const wrongUtc = Date.UTC(
  localDate.getFullYear(),
  localDate.getMonth(),
  localDate.getDate(),
  localDate.getHours(),
  localDate.getMinutes()
);
// This double-applies the timezone offset!

// FIX: just use the timestamp directly
const correct = new Date(utcTs * 1000);
console.log(correct.toISOString());
// Always returns UTC, no offset issues

When debugging timestamp issues, our Unix Timestamp Converter is invaluable for quickly checking what a given numeric value actually represents.

Timestamps in Different Languages: Quick Reference

LanguageGet Current TimestampUnit
JavaScriptDate.now()Milliseconds
Pythontime.time()Seconds (float)
PHPtime()Seconds
RubyTime.now.to_iSeconds
JavaSystem.currentTimeMillis()Milliseconds
Gotime.Now().Unix()Seconds
RustSystemTime::now().duration_since(UNIX_EPOCH)Duration (seconds + nanos)
Ctime(NULL)Seconds
Bashdate +%sSeconds
SQL (PostgreSQL)EXTRACT(EPOCH FROM NOW())Seconds (float)

Notable Timestamps and Milestones

Some timestamps hold special significance in the computing world:

TimestampDate (UTC)Significance
01970-01-01 00:00:00The Unix Epoch
10000000002001-09-09 01:46:40Billennium (10-digit milestone)
12345678902009-02-13 23:31:30Sequential digits
17000000002023-11-14 22:13:201.7 billion seconds
20000000002033-05-18 03:33:202 billion seconds
21474836472038-01-19 03:14:0732-bit signed integer max (Y2K38)
42949672952106-02-07 06:28:1532-bit unsigned integer max

You can verify any of these using our Timestamp Converter tool.

Negative Timestamps: Dates Before 1970

Unix timestamps can be negative to represent dates before January 1, 1970. For example, -86400 represents December 31, 1969, and -2208988800 represents January 1, 1900. Most modern languages handle negative timestamps correctly:

// JavaScript: supports negative timestamps
const moonLanding = new Date("1969-07-20T20:17:00Z");
console.log(Math.floor(moonLanding.getTime() / 1000));
// -14182580

// Python: supports negative timestamps
from datetime import datetime, timezone
dt = datetime(1969, 7, 20, 20, 17, 0, tzinfo=timezone.utc)
print(int(dt.timestamp()))
# -14182580

Timestamp Precision: When Seconds Are Not Enough

For applications that require sub-second precision (distributed tracing, financial trading, high-frequency logging), you will need timestamps with more than second-level granularity:

// JavaScript: Performance API for microsecond precision
const highResTs = performance.now(); // milliseconds, sub-ms precision
console.log(highResTs); // 1234.567890

// Node.js: nanosecond precision
const [seconds, nanoseconds] = process.hrtime();
console.log(seconds, nanoseconds); // 123456 789012345

// Go: nanosecond precision
import "time"
ts := time.Now().UnixNano()
// 1772150400000000000

// Rust: nanosecond precision
use std::time::{SystemTime, UNIX_EPOCH};
let ts = SystemTime::now()
    .duration_since(UNIX_EPOCH)
    .unwrap()
    .as_nanos();
// 1772150400000000000

Database Timestamp Types: A Comparison

DatabaseTypeRangePrecision
PostgreSQLTIMESTAMPTZ4713 BC to 294276 ADMicrosecond
MySQLTIMESTAMP1970-01-01 to 2038-01-19Second
MySQLDATETIME1000-01-01 to 9999-12-31Second
SQLiteINTEGERFull 64-bit rangeSecond
MongoDBDate64-bit ms since epochMillisecond

Recommendation: For PostgreSQL, always use TIMESTAMPTZ (timestamp with timezone). For MySQL, prefer DATETIME over TIMESTAMP to avoid the 2038 limit. If you need precise control and want to avoid ORM timezone surprises, store Unix timestamps as BIGINT.

Auto-Detecting Timestamp Precision

When receiving timestamps from external APIs or user input, you often need to auto-detect whether the value is in seconds, milliseconds, or microseconds. Here is a reliable approach:

function normalizeTimestamp(ts: number): Date {
  // Microseconds: 16 digits (e.g., 1772150400000000)
  if (ts > 1e15) {
    return new Date(ts / 1000);
  }
  // Milliseconds: 13 digits (e.g., 1772150400000)
  if (ts > 1e12) {
    return new Date(ts);
  }
  // Seconds: 10 digits (e.g., 1772150400)
  return new Date(ts * 1000);
}

// Usage
console.log(normalizeTimestamp(1772150400).toISOString());
// "2026-02-27T00:00:00.000Z"
console.log(normalizeTimestamp(1772150400000).toISOString());
// "2026-02-27T00:00:00.000Z"
console.log(normalizeTimestamp(1772150400000000).toISOString());
// "2026-02-27T00:00:00.000Z"

Generating Timestamps on the Command Line

Sometimes you need to quickly get or convert timestamps from the terminal:

# Current Unix timestamp (seconds)
date +%s
# 1772150400

# Current timestamp in milliseconds
date +%s%3N
# 1772150400000

# Convert timestamp to human-readable date (Linux/GNU)
date -d @1772150400
# Fri Feb 27 00:00:00 UTC 2026

# Convert timestamp to human-readable date (macOS/BSD)
date -r 1772150400
# Fri Feb 27 00:00:00 UTC 2026

# Convert date string to timestamp (Linux/GNU)
date -d "2026-02-27T12:00:00Z" +%s
# 1772193600

# Convert date string to timestamp (macOS/BSD)
date -j -f "%Y-%m-%dT%H:%M:%SZ" "2026-02-27T12:00:00Z" +%s
# 1772193600

Best Practices Summary

  1. Store UTC: Always store and transmit timestamps in UTC. Convert to local time only for display.
  2. Use 64-bit integers: Avoid 32-bit timestamps to prevent Y2K38 issues. Use BIGINT in databases.
  3. Document your precision: Explicitly state whether your API uses seconds or milliseconds in your documentation.
  4. Validate inputs: Auto-detect timestamp precision using digit count (10 = seconds, 13 = milliseconds).
  5. Use ISO 8601 for human-readable formats: Always output dates in ISO 8601 format when a string representation is needed.
  6. Prefer timezone names over offsets: Use IANA timezone names (America/New_York) instead of fixed offsets (-05:00).
  7. Test edge cases: Test with timestamps near DST transitions, the Unix epoch (0), negative timestamps, and the Y2K38 boundary.
  8. Use libraries for complex operations: For anything beyond basic conversions, use established libraries like dayjs, date-fns, or Luxon in JavaScript, or pendulum / arrow in Python.

For quick timestamp conversions during development and debugging, bookmark our Unix Timestamp Converter tool. It handles seconds, milliseconds, and microsecond timestamps and shows the result in multiple timezones simultaneously.

Frequently Asked Questions

What is a Unix timestamp?

A Unix timestamp (also called Epoch time or POSIX time) is the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC. It provides a timezone-independent, integer-based way to represent a specific moment in time. For example, the timestamp 1772150400 represents February 27, 2026, at midnight UTC.

How do I convert a Unix timestamp to a date in JavaScript?

Use new Date(timestamp * 1000) if your timestamp is in seconds, or new Date(timestamp) if it is in milliseconds. JavaScript's Date constructor expects milliseconds, so you must multiply second-precision timestamps by 1000. Then call .toISOString() for UTC or .toLocaleString() for a localized format.

Why is my date showing January 1, 1970?

This happens when a timestamp value of 0 (or near zero) is converted to a date, since timestamp 0 equals the Unix epoch (January 1, 1970). Common causes include: passing a second-precision timestamp to a function that expects milliseconds, using a null or undefined value that defaults to 0, or a failed string-to-number conversion that produces NaN (which may be coerced to 0).

What is the difference between seconds and milliseconds timestamps?

A second-precision Unix timestamp is a 10-digit number (e.g., 1772150400) counting seconds since the epoch. A millisecond-precision timestamp is a 13-digit number (e.g., 1772150400000) counting milliseconds. JavaScript, Java, and Dart use milliseconds natively, while Python, PHP, C, Go, and most Unix tools use seconds. Always check your digit count to determine which format you are working with.

What is the Y2K38 problem?

The Y2K38 problem (Year 2038 problem) occurs because 32-bit signed integers can only represent timestamps up to 2,147,483,647, which corresponds to January 19, 2038 at 03:14:07 UTC. After this moment, the integer overflows and wraps to a negative number, causing the date to jump back to December 1901. To avoid this, use 64-bit integers for timestamp storage. Most modern 64-bit systems, JavaScript, and Python are already safe.

Should I use Unix timestamps or ISO 8601 strings in my API?

Both are valid choices. Unix timestamps (integers) are compact, unambiguous, and easy to sort. ISO 8601 strings (e.g., "2026-02-27T12:00:00Z") are human-readable and self-documenting. Many modern APIs prefer ISO 8601 for JSON responses because they are immediately understandable without conversion. Some large APIs provide both formats. The key is to be consistent and document your choice clearly.

How do I handle timezones correctly with Unix timestamps?

Unix timestamps are inherently UTC, so there is no timezone ambiguity in the stored value. The best practice is to always store and transmit timestamps in UTC, then convert to the user's local timezone only in the presentation layer (frontend). Use IANA timezone names like "America/New_York" instead of fixed offsets like "-05:00" because timezone names correctly handle daylight saving time transitions.

Can Unix timestamps represent dates before 1970?

Yes, negative Unix timestamps represent dates before the epoch. For example, -86400 represents December 31, 1969, and -2208988800 represents January 1, 1900. Most modern programming languages (JavaScript, Python, Go, Rust) handle negative timestamps correctly. However, some older systems and database types may not support negative timestamps, so test your specific platform.

𝕏 Twitterin LinkedIn
Var detta hjälpsamt?

Håll dig uppdaterad

Få veckovisa dev-tips och nya verktyg.

Ingen spam. Avsluta när som helst.

Try These Related Tools

🕐Unix Timestamp Converter{ }JSON FormatterJWTJWT Decoder

Related Articles

Unix Timestamp till datum: Konvertera i JavaScript, Python, Bash, SQL

Konvertera Unix-timestamps till läsbara datum.

JavaScript datumformat: Komplett guide

Lär dig alla sätt att formatera datum i JavaScript: toLocaleDateString, Intl.DateTimeFormat, ISO och populära bibliotek.

REST API Best Practices: Den Kompletta Guiden för 2026

Lär dig REST API design best practices: namnkonventioner, felhantering, autentisering och säkerhet.

Hur JWT fungerar: Komplett guide till JSON Web Tokens

Lär dig hur JWT-autentisering fungerar med header, payload och signatur.