SoftwareSideHustles
How-To

Dates, Times and Time Zones: How to Get Them Right in Python, JavaScript and Java

Store UTC, display local time, and avoid the classic date bugs — zero-indexed months in JavaScript, naive datetimes in Python, YYYY in Java format patterns, daylight saving time and seconds versus milliseconds.

By Software Side Hustles Editorial Team · Published · Updated · 5 min read

Quick answer: store and transmit timestamps in UTC using ISO 8601 (2026-10-26T09:00:00Z), convert to the user's time zone only when displaying, and use time-zone-aware types: Python datetime.now(timezone.utc), JavaScript new Date().toISOString(), Java Instant.now(). Most date bugs come from mixing "a moment in time" with "a date on a calendar".

Current time in UTC, by language

LanguageCurrent UTC momentISO 8601 stringUnix timestamp
Pythondatetime.now(timezone.utc).isoformat()time.time() (seconds, float)
JavaScriptnew Date().toISOString()Date.now() (milliseconds)
JavaInstant.now().toString()Instant.now().getEpochSecond()
C#DateTimeOffset.UtcNow.ToString("O").ToUnixTimeSeconds()
Gotime.Now().UTC().Format(time.RFC3339).Unix()
PostgreSQLnow()—extract(epoch from now())

Note the units column. Mixing JavaScript milliseconds with Unix seconds from a backend produces dates in 1970 or the year 58,000.

Instants versus calendar dates

There are two different things people call "a date":

  • An instant — a single moment worldwide, such as "the payment was captured". Store it in UTC.
  • A local date or time — a calendar value, such as a birthday, a public holiday or "the shop opens at 09:00". It has no time zone, and converting it to UTC is a bug: a birthday stored as midnight UTC shows up as the previous day for users in New York.

Choose the type that matches: Java's Instant versus LocalDate, PostgreSQL's timestamptz versus date, Python's aware datetime versus date.

Dates and time zones in Python

python
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo
now = datetime.now(timezone.utc) # aware, UTC
london = now.astimezone(ZoneInfo("Europe/London")) # same instant, local wall time
parsed = datetime.fromisoformat("2026-10-26T09:00:00Z") # 'Z' accepted on Python 3.11+
parsed.strftime("%d %b %Y %H:%M") # '26 Oct 2026 09:00'

Python has naive datetimes (no time zone) and aware ones. Comparing the two raises TypeError: can't compare offset-naive and offset-aware datetimes. Make everything aware at the edges of your program and the error disappears. datetime.utcnow() is deprecated since Python 3.12 precisely because it returns a naive value that looks like UTC but is not marked as such; use datetime.now(timezone.utc).

Dates and time zones in JavaScript

javascript
const now = new Date();
now.toISOString(); // "2026-10-26T09:00:00.000Z" — always UTC
new Intl.DateTimeFormat("en-GB", { dateStyle: "medium", timeStyle: "short", timeZone: "Europe/London" }).format(now);

JavaScript's Date has well-known traps:

javascript
new Date(2026, 0, 15); // 15 January — months are 0-indexed, days are not
new Date("2026-01-15"); // parsed as midnight UTC
new Date("2026-01-15T00:00"); // parsed as midnight LOCAL time

The last two lines look almost identical and differ by your UTC offset. A user west of Greenwich sees new Date("2026-01-15").getDate() return 14. When you need a calendar date, keep it as a "YYYY-MM-DD" string or use a date library (date-fns, Luxon, Day.js) rather than Date. Newer runtimes are adding the Temporal API, which separates instants from plain dates properly; check support in your target environments before relying on it.

Dates and time zones in Java

java
Instant now = Instant.now();
ZonedDateTime paris = now.atZone(ZoneId.of("Europe/Paris"));
LocalDate birthday = LocalDate.of(1990, 5, 17);
String shown = paris.format(DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm"));

Use java.time (Java 8+). The old java.util.Date and SimpleDateFormat are mutable, confusing and SimpleDateFormat is not thread-safe — sharing one across threads produces corrupt dates under load.

The Java formatting trap that bites every December:

java
LocalDate.of(2025, 12, 29).format(DateTimeFormatter.ofPattern("YYYY-MM-dd")); // "2026-12-29"
LocalDate.of(2025, 12, 29).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // "2025-12-29"

YYYY is the week-based year, which differs from the calendar year for a few days around New Year. Use yyyy (or uuuu). The same pattern letter causes the same bug in Swift and other ICU-based formatters. Similarly, mm is minutes and MM is months; hh is a 12-hour clock and HH is 24-hour.

Daylight saving time bugs

  • "Add one day" is not "add 24 hours". On the day clocks change, a local day has 23 or 25 hours. Use calendar arithmetic (plusDays(1) on a ZonedDateTime, timedelta(days=1) on a local date) for "same time tomorrow", and duration arithmetic for "24 hours from now".
  • Some local times do not exist (the hour skipped in spring) and some happen twice (the hour repeated in autumn). Scheduling "2:30 every night" needs a rule for both.
  • Fixed offsets are not time zones. +01:00 is an offset; Europe/London is a zone whose offset changes. Store the IANA zone name for future events such as meetings.

Storing dates in a database

Use PostgreSQL timestamptz (it stores UTC and converts on the way in and out) for instants, date for calendar dates, and keep the database session's time zone at UTC. In MySQL, TIMESTAMP converts to UTC while DATETIME does not. Do not store dates as formatted strings such as "26/10/2026" — they do not sort or compare correctly. See sorting by a property.

Frequently asked questions

What is ISO 8601?

The international standard format YYYY-MM-DDTHH:MM:SS with an offset or Z for UTC, e.g. 2026-10-26T09:00:00Z. It is unambiguous, and strings in the same offset sort chronologically.

How do I convert a Unix timestamp to a date?

Python datetime.fromtimestamp(ts, timezone.utc), JavaScript new Date(ts * 1000) (seconds to milliseconds), Java Instant.ofEpochSecond(ts).

How do I calculate the difference between two dates in days?

Subtract calendar dates, not timestamps: (date2 - date1).days in Python, ChronoUnit.DAYS.between(d1, d2) in Java. Dividing a millisecond difference by 86,400,000 is off by one across DST changes.

Should I use a date library?

In JavaScript, usually yes for anything beyond formatting. In Python and Java the standard libraries (datetime + zoneinfo, java.time) are good enough for most applications.

Where this skill pays off

Date handling is where confident-looking AI code is most often wrong: naive datetimes, YYYY patterns, off-by-one days in other time zones. Our free exchange-rate cache exercise includes a freshness check that depends on getting time right. Reviewing that kind of code is paid work — read how developers earn money training AI models.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy