How to Convert a String to a Date in PostgreSQL (2024)

Problem:

You’d like to convert a string containing a date to the PostgreSQL date data type.

Example:

Let’s convert a date string to the date data type instead of its current text data type.

How to Convert a String to a Date in PostgreSQL (1)

Solution:

Here’s Example 1 of how to use the TO_DATE() function. This is the query you would write:

SELECT TO_DATE('20230304', 'YYYYMMDD') AS new_date;

And here’s the result of the query:

new_date
2023-03-04

Let’s look at Example 2 of the TO_DATE() function. Notice the slightly different date format:

SELECT TO_DATE('2023/06/07', 'YYYY/MM/DD') AS new_date;

Here’s the result of the query:

new_date
2023-06-07

Discussion:

Use the function TO_DATE() to convert a text value containing a date to the date data type. This function takes two arguments:

  1. A date value. This can be a string (a text value) or a text column containing date information. In our example, we used the strings '20230304' and '2023/06/07'.
  2. The input date format. In our example, we used 'YYYYMMDD' and 'YYYY/MM/DD'. Notice that the input format is a string.

How to Convert a String to a Date in PostgreSQL (2)

The input format decides how PostgreSQL will process the characters in the string where the date is stored. The specifier YYYY as the first four characters indicates that these represent a 4-digit year. Next, MM represents a 2-digit month and DD a 2-digit day. You can find a list of all specifiers in the PostgreSQL documentation.

In Example 1, the string date '20230304' was converted to the date value of 2023-03-04 (a date data type). In Example 2, the string '2023/06/07' was converted to the date value of 2023-06-07. In the second example, we used the slash / between date parts to correctly convert from a string to the date data type.

How to Convert a String to a Date in PostgreSQL (2024)
Top Articles
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 6468

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.