Fast Date / Time Calcs for Developers: From Epochs to Timezones
Understanding and manipulating dates and times is a routine but error-prone task for developers. This guide gives a concise, practical set of patterns and code examples to handle common needs: epoch timestamps, date arithmetic, timezones, daylight saving time (DST), and formatting/parsing. Examples use JavaScript (Node.js) and Python — adjust for your language as needed.
1. Representations: epochs, ISO, and native objects
- Epoch (seconds or milliseconds): simple integer for storage/compare.
- ISO 8601 string: human-readable and timezone-aware (e.g., 2026-05-12T14:30:00Z).
- Native objects: Date (JS), datetime (Python) for operations.
JavaScript (UTC epoch ms):
javascript
const nowMs = Date.now(); // milliseconds since 1970-01-01T00:00:00Zconst nowIso = new Date(nowMs).toISOString();
Python (UTC epoch s):
python
import timenow_s = int(time.time()) # seconds since epochfrom datetime import datetime, timezonenow_iso = datetime.now(timezone.utc).isoformat()
2. Basic arithmetic: add/subtract intervals
Principle: operate in UTC when possible; convert to local only for display.
JavaScript — add days safely:
javascript
function addDays(date, days) { const d = new Date(date); d.setUTCDate(d.getUTCDate() + days); return d;}
Python — use timedelta:
python
from datetime import timedelta, datetime, timezonedt = datetime.now(timezone.utc)dt_plus_3 = dt + timedelta(days=3)
For months/years prefer libraries (see “Libraries” below) because month lengths vary.
3. Differences and durations
Compute differences in seconds/ms and convert.
JS:
javascript
const diffMs = new Date(end) - new Date(start);const diffSeconds = Math.floor(diffMs / 1000);
Python:
python
delta = end_dt - start_dtseconds = int(delta.total_seconds())
Show durations human-readably by extracting days/hours/minutes/seconds.
4. Timezones and DST
Always store timestamps in UTC (epoch or ISO with Z). Convert to timezones only at presentation. Beware DST when adding “calendar” units (e.g., add 1 day across DST might be 23 or 25 hours in local time).
JavaScript (Intl for formatting; luxon example for conversion):
javascript
// Intl.DateTimeFormat for displayconst fmt = new Intl.DateTimeFormat(‘en-US’, { timeZone: ‘America/New_York’, dateStyle: ‘medium’, timeStyle: ‘short’ });fmt.format(new Date()); // Luxon (recommended over Date for heavy timezone work)import { DateTime } from ‘luxon’;DateTime.fromISO(‘2026-03-13T01:30:00’, { zone: ‘America/New_York’ }).plus({ hours: 2 }).toISO();
Python (zoneinfo or pytz):
python
from datetime import datetimefrom zoneinfo import ZoneInfodt = datetime(2026,3,13,1,30, tzinfo=ZoneInfo(“America/New_York”))dt_plus = dt + timedelta(hours=2)