How to Format a Date in PostgreSQL
Database:
Operators:
Table of Contents
Problem
You want to format a date column or value in PostgreSQL.
Example
The company’s database has a table named employees with data in the columns first_name, last_name, and hire_date.
| first_name | last_name | hire_date |
|---|---|---|
| Agatha | Smith | 2021-03-15 |
| William | Parker | 2022-01-22 |
| Noah | Crawford | 2009-10-01 |
We want to extract the information for each employee, but we want to have hire_date in the dd/mm/yyyy format (e.g. 03/12/2022).
Solution
Here’s how you would solve this problem:
SELECT first_name, last_name, TO_CHAR(hire_date, 'dd/mm/yyyy') FROM employees;
And here’s the result you would get:
| first_name | last_name | hire_date |
|---|---|---|
| Agatha | Smith | 15/03/2021 |
| William | Parker | 22/01/2022 |
| Noah | Crawford | 01/10/2009 |
Discussion
To format a date in PostgreSQL use the function TO_CHAR(). This function takes a date, formats it to your definition, and returns a string. It requires two parameters: a date value and a format. The format is a string (text) pattern specifying what the date should look like. It contains placeholders for date elements (e.g. YYYY is the placeholder for a 4-digit year) and the punctuation to be used in the date format.
Some popular examples of date formats are:
YYYY-MM-DDYYYY- year (4 digits)MM- month number (01–12)DD- day of month (01–31)- Elements are separated by a hyphen (
-) - Sample output:
2022-03-24
DD/MM/YYYYYYYY- year (4 digits)MM- month number (01–12)DD- day of month (01–31)- Elements are separated by a forward slash (
/) - Sample output:
24/03/2022
Month DD, YYYYMonth- Capitalized full month name (e.g.FebruaryorMay)- The month and day are separated from the year by a comma
- Sample output:
March 24, 2022
DD-MON-YYMON- Abbreviated upper case month name (e.g.FEBfor February orDECfor December)YY- Last 2 digits of year- Sample output:
24-MAR-22
All possible format options can be found in the official PostgreSQL documentation.