PostgreSQL – How to Convert Date to String

You can convert a date to a string using the TO_CHAR function in PostgreSQL database. TO_CHAR function allows you to format the date as a string with a specific format. Here’s how you can do it:

SELECT TO_CHAR(your_date_column, 'YYYY-MM-DD') AS date_string FROM your_table;

In the above syntax,

  • your_date_column is the name of the date column you want to convert to a string.
  • your_table is the name of the table where the date column resides.

The format string 'YYYY-MM-DD' specifies the desired format for the resulting string. You can customize the format to meet your requirements. In this example, the format represents the year (YYYY), month (MM), and day (DD) components of the date, separated by hyphens.

For instance, if you want to use a different date format, you can adjust the format string accordingly. Here are a few examples:

Convert to a date in a different format (e.g., MM/DD/YYYY):

SELECT TO_CHAR(transaction_date, 'MM/DD/YYYY') AS date_string FROM sales;

Output of above select statement is shown in the screenshot below:

Convert to a date with the month spelled out (e.g., September 20, 2023):

SELECT TO_CHAR(transaction_date, 'Month, DD, YYYY') AS date_string FROM sales;

Output to above sql is shown in the screenshot below:

You can modify the format string as needed to get the desired representation of the date as a string.

Similar Posts