← Back to PostgreSQL Course | Chapter 5: Filtering & Functions | Lesson 3 of 7

Date functions

Date functions read the current time, extract parts and do arithmetic with intervals.

In this page:

  1. Date functions
Syntax
sql
SELECT now(), CURRENT_DATE;
SELECT EXTRACT(field FROM date_column) FROM table_name;
SELECT date_column + INTERVAL 'n days' FROM table_name;

Date functions

now() and CURRENT_DATE return the current time and date. EXTRACT(field FROM date) returns parts such as year, month, dow and epoch, date_trunc(month, ts) rounds down to a unit, age(a, b) gives an interval, and to_char formats dates as text.

Adding INTERVAL values shifts dates.

Note: date_trunc is the easiest way to group by month.

Example: Date functions

bash
shop=# SELECT EXTRACT(year FROM DATE '2024-03-15') AS y, EXTRACT(dow FROM DATE '2024-03-15') AS weekday;
  y   | weekday
------+---------
 2024 |       5
shop=# SELECT date_trunc('month', TIMESTAMP '2024-03-15 10:30:00') AS month_start;
     month_start
---------------------
 2024-03-01 00:00:00
shop=# SELECT age(DATE '2024-03-15', DATE '2000-01-01') AS age;
           age
-------------------------
 24 years 2 mons 14 days
shop=# SELECT DATE '2024-03-15' + INTERVAL '1 month' AS next_month;
      next_month
---------------------
 2024-04-15 00:00:00

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Formatting dates as text for comparison
  2. Ignoring time zones with now()
  3. Using string concatenation for date arithmetic
Chapter Summary
  • now() and CURRENT_DATE
  • EXTRACT gets parts
  • date_trunc rounds down
  • INTERVAL adds durations
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.