A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgresql-format-date.php below:

Website Navigation


How to Format Dates in PostgreSQL with examples?

How to Format Dates in PostgreSQL with examples?Last update on December 31 2024 05:34:50 (UTC/GMT +8 hours)

PostgreSQL Date Formatting Explained

Formatting dates in PostgreSQL is essential for displaying date values in a user-friendly or specific format. PostgreSQL provides several functions, such as TO_CHAR, to customize how date and time data appear. This guide explores the syntax, examples, and best practices for formatting dates in PostgreSQL.

Syntax:

To format a date in PostgreSQL, the most commonly used function is TO_CHAR.

TO_CHAR(date_value, 'format')

Components:

Common Formatting Patterns

Pattern Description Example YYYY Year (4 digits) 2024 YY Year (2 digits) 24 MM Month (2 digits) 01 Mon Abbreviated month name Jan Month Full month name January DD Day of the month 15 Day Full day name Monday DY Abbreviated day name Mon HH24 Hour (24-hour format) 13 HH12 Hour (12-hour format) 01 MI Minutes 45 SS Seconds 30

Examples and Code:

1. Format Date to YYYY-MM-DD

Code:

-- Format a date to 'YYYY-MM-DD'
SELECT TO_CHAR(CURRENT_DATE, 'YYYY-MM-DD') AS formatted_date;

Output:

formatted_date  
--------------
2024-01-15

2. Display Full Month and Year

Code:

-- Display date as 'Month YYYY'
SELECT TO_CHAR(CURRENT_DATE, 'Month YYYY') AS formatted_date;

Output:

formatted_date  
--------------
January 2024

3. Custom Format with Day, Month, and Time

Code:

-- Display date as 'Day, DD Mon YYYY HH12:MI AM'
SELECT TO_CHAR(NOW(), 'Day, DD Mon YYYY HH12:MI AM') AS formatted_date_time;

Output:

formatted_date_time  
--------------------
Monday, 15 Jan 2024 01:30 PM

4. Retrieve Month and Day Separately

Code:

-- Get the month and day separately
SELECT 
    TO_CHAR(CURRENT_DATE, 'MM') AS month,
    TO_CHAR(CURRENT_DATE, 'DD') AS day;

Output:

month | day  
------+-----
01    | 15

Explanation

Common Errors and Tips

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4