Memra

Dates & time

◈ 2 cards

Extract parts, filter by date, and do date math.

Working with dates

Postgres has first-class date, timestamp, and interval types. Useful tools:

  • CURRENT_DATE, now() — today / this instant
  • EXTRACT(YEAR FROM d), EXTRACT(MONTH FROM d) — pull out a part
  • date_trunc('month', d) — round down to the start of a unit
  • age(d), d + INTERVAL '7 days' — date arithmetic
  • to_char(d, 'YYYY-MM') — format as text
SELECT id, ordered_at + INTERVAL '30 days' AS due FROM orders;
expressionresultEXTRACT(YEAR FROM ordered_at)2023EXTRACT(MONTH FROM ordered_at)3date_trunc('month', ordered_at)2023-03-01ordered_at + INTERVAL '30 days'2023-04-09to_char(ordered_at, 'YYYY-MM')'2023-03'Order 3 was placed on 2023-03-10.
EXTRACT pulls a number out of a date, date_trunc rounds a date down to the start of a unit, and adding an interval gives another date. Only to_char returns text.
NORMAL ~/memra/learn/postgresql/dates-and-time utf-8 LF