Convert DATE or TIMESTAMP values to human-readable text using format patterns.
Applications, reports, and logs often need dates shown in a user-friendly style (e.g., “14-Feb-2024” instead of “2024-02-14”). Formatting inside SQL lets you keep presentation logic close to the data and avoid extra code in the app layer.
Use TO_CHAR()
. It accepts any date/time type and a format pattern string. Pattern tokens are case-sensitive, so YYYY
differs from yyyy
.
SELECT TO_CHAR(CURRENT_DATE, 'DD-Mon-YYYY'); -- 14-Feb-2024
Replace DD-Mon-YYYY
with any combination of tokens (see below) to match the desired output.
YYYY
– four-digit yearYY
– two-digit yearMM
– month number (01-12)Mon
/Month
– abbreviated/full month nameDD
– day of monthHH24
/MI
/SS
– 24-hour timeTZ
– time-zone abbreviationSet lc_time
at session level: SET lc_time = 'de_DE';
TO_CHAR(NOW(), 'DD Mon YYYY')
then returns German names.
Enclose text in double quotes inside the pattern: TO_CHAR(NOW(), 'FM"Week:" IW, YYYY')
.
Convert the value first: SELECT TO_CHAR(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI') AS utc_ts;
PostgreSQL already outputs ISO 8601 with to_json
, but you can force it: TO_CHAR(ts, 'YYYY-MM-DD"T"HH24:MI:SSOF')
.
Add FM
(fill mode) at the start of the pattern to suppress leading blanks and zeros: TO_CHAR(DATE '2024-02-02', 'FMMon DD')
→ Feb 2
.
format()
function useful?format()
is for building strings. Combine it with to_char
: SELECT format('Report date: %s', to_char(CURRENT_DATE, 'DD Mon YYYY'));
Keep raw columns as DATE
/TIMESTAMP
, perform formatting only in the final SELECT layer, and document patterns in code comments for maintainability.
Yes, TO_CHAR is the canonical function. Casting to TEXT implicitly uses the server’s default format, but that is not safe for end-users or APIs.
You can, but avoid it. Store raw date/time types and generate strings on demand; this prevents duplication and eases localization changes.
Use justify_interval()
for human-friendly intervals or to_char()
if you need a custom display, although fewer pattern tokens are available.