Converting Date to Epoch

How to convert a human-readable date to a Unix epoch timestamp in multiple languages. Covers timezone considerations and common parsing mistakes.

Conversion

2024-01-01 → 1704067200

Detailed Explanation

Converting a human-readable date to a Unix epoch timestamp is the reverse of epoch-to-date conversion, but it comes with additional complexity because you must decide what timezone the input date is in before converting.

The timezone question: The string "2024-01-01 00:00:00" is ambiguous without a timezone. Is it midnight in UTC, New York, or Tokyo? Each interpretation produces a different Unix timestamp:

2024-01-01 00:00:00 UTC       → 1704067200
2024-01-01 00:00:00 US/Eastern → 1704085200  (+5 hours)
2024-01-01 00:00:00 Asia/Tokyo → 1704034800  (-9 hours)

Conversion in major languages:

// JavaScript
new Date("2024-01-01T00:00:00Z").getTime() / 1000
// 1704067200

// Without 'Z', behavior varies by browser! Always include timezone.
# Python
from datetime import datetime, timezone
dt = datetime(2024, 1, 1, tzinfo=timezone.utc)
int(dt.timestamp())
# 1704067200

# Parsing a string
from datetime import datetime
dt = datetime.strptime("2024-01-01", "%Y-%m-%d")
# WARNING: this is naive (no timezone) — .timestamp() assumes local time
// Java
LocalDate.parse("2024-01-01")
    .atStartOfDay(ZoneOffset.UTC)
    .toEpochSecond()
// 1704067200
-- MySQL
SELECT UNIX_TIMESTAMP('2024-01-01 00:00:00');

-- PostgreSQL
SELECT EXTRACT(EPOCH FROM '2024-01-01 00:00:00 UTC'::timestamptz);

Common pitfalls:

In Python, calling .timestamp() on a naive datetime (one without timezone info) assumes local time, which will give different results depending on which machine runs the code. Always attach a timezone to your datetime before converting.

In JavaScript, date-only strings like "2024-01-01" are parsed as UTC, but date-time strings like "2024-01-01T00:00:00" (without Z or offset) are parsed as local time. This inconsistency in the ECMAScript spec has been a long-standing source of confusion.

Validation: Before converting user input, validate the date. Invalid dates like February 30 or month 13 may produce unexpected results rather than errors in some languages. Use strict parsing modes where available.

Use Case

When building a reporting dashboard with date range filters, you must convert the user's selected dates to epoch timestamps in their timezone to query the database accurately.

Try It — Timestamp Converter

Open full tool