Storing Dates and Times Without Getting Confused

Dates look simple until a bug appears at midnight or when the clocks change. Most of the confusion comes from a few decisions made early. This post explains those decisions in plain terms, so your first app stores time sensibly.

Moving data to a new database illustration

Decision 1: date, or date and time?

Use the simplest one that fits. Storing a birthday as a timestamp at midnight invites time-zone problems for no benefit.

Decision 2: which time zone?

A timestamp without a time zone is ambiguous. "09:30" in Lisbon is not "09:30" in Lagos.

A common, beginner-friendly rule: store timestamps in UTC, the world reference time, and convert to the user's local time only when displaying. Then every stored value means the same instant, wherever the server or user is.

How the databases handle it

DatabaseCommon typesNotes
PostgreSQLdate, timestamp, timestamptztimestamptz stores an instant and converts for display based on session settings
MySQLDATE, DATETIME, TIMESTAMPTIMESTAMP is converted using the session time zone; DATETIME is stored as given
SQLiteNo dedicated date typeStore ISO 8601 text such as 2026-03-14T09:30:00Z, or numbers; date functions understand both

Check your database's documentation for the exact behaviour; time handling is one area where details really matter.

Use the ISO 8601 format

ISO 8601 is the international standard format: year, month, day, from biggest to smallest, like 2026-03-14. It has a lovely property: when stored as text, sorting alphabetically also sorts by date. Formats like 14/03/2026 do not sort correctly as text and are ambiguous between countries.

Comparing dates safely

To find orders on one day, compare with a range rather than with a function on the column:

SELECT id FROM orders
WHERE placed_at >= '2026-03-14'
  AND placed_at <  '2026-03-15';

This is clear, works across databases, and lets an index on placed_at help later.

Let the database fill in "now"

Instead of sending the time from your program, which may have the wrong clock or zone, many databases can set it for you:

CREATE TABLE notes (
  id         INTEGER PRIMARY KEY,
  body       TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

In SQLite, CURRENT_TIMESTAMP gives UTC in the format YYYY-MM-DD HH:MM:SS.

Common beginner bugs

The short version

Use a date type for dates, UTC timestamps for moments, ISO 8601 formats everywhere, and ranges for comparisons. Our guide to SQL data types when you are just starting covers the other types you will meet.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site