Getting Midnight Timestamp

How to get the Unix timestamp for midnight (start of day) in any timezone. Covers floor-to-day operations, DST edge cases, and database date grouping.

Conversion

00:00:00

Detailed Explanation

Getting the Unix timestamp for the start of a day (midnight, 00:00:00) is essential for date-based grouping, daily aggregations, and setting date range boundaries. The challenge is that "midnight" depends on the timezone — midnight in New York is a different instant than midnight in Tokyo.

Midnight in UTC:

// JavaScript: midnight UTC today
const now = new Date();
const midnightUTC = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
midnightUTC / 1000  // Unix timestamp in seconds
# Python: midnight UTC today
from datetime import datetime, timezone
today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
int(today.timestamp())

Midnight in a specific timezone:

// JavaScript: midnight in US Eastern
const eastern = new Date(
  new Date().toLocaleString("en-US", { timeZone: "America/New_York" })
);
eastern.setHours(0, 0, 0, 0);
// But this approach has edge cases — prefer Temporal API or a library
# Python: midnight in US Eastern
from datetime import datetime
from zoneinfo import ZoneInfo
tz = ZoneInfo("America/New_York")
local_now = datetime.now(tz)
midnight = local_now.replace(hour=0, minute=0, second=0, microsecond=0)
int(midnight.timestamp())

Floor-to-day using integer math:

A quick way to compute midnight UTC from a Unix timestamp is integer division:

midnight_utc = (timestamp // 86400) * 86400

This works for UTC only. For other timezones, you must first apply the offset, floor, then subtract the offset.

The DST midnight problem:

In some timezones, midnight may not exist on certain days. In Brazil, when spring-forward DST transitions happen at midnight, the clock jumps from 23:59:59 directly to 01:00:00. In these cases, the "start of day" is 01:00:00, not 00:00:00. Robust date libraries handle this correctly, but manual calculations break.

Database grouping by day: When aggregating data by date in SQL, always apply the timezone before truncating to a day. In PostgreSQL: DATE_TRUNC('day', timestamp AT TIME ZONE 'America/New_York').

Use Case

E-commerce dashboards that show daily sales figures must compute midnight timestamps in the merchant's local timezone to align report boundaries with the business day, not the UTC day.

Try It — Timestamp Converter

Open full tool