Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL : cast string to date DD/MM/YYYY

I'm trying to cast a CHARACTER VARYING column to a DATE but I need a date format like this : DD/MM/YYYY. I use the following SQL query :

ALTER TABLE test  ALTER COLUMN date TYPE DATE using to_date(date, 'DD/MM/YYYY'); 

The result is a date like this : YYYY-MM-DD.

How can I get the DD/MM/YYYYformat ?

Thanks a lot in advance !

Thomas

like image 282
wiltomap Avatar asked Jun 19 '14 08:06

wiltomap


People also ask

How do I convert text to date in PostgreSQL?

The TO_DATE function in PostgreSQL is used to converting strings into dates. Its syntax is TO_DATE(text, text) and the return type is date. The TO_TIMESTAMP function converts string data into timestamps with timezone. Its syntax is to_timestamp(text, text) .

How do I change the date format from YYYY-MM-DD in PostgreSQL?

1) Get the current date To get the current date and time, you use the built-in NOW() function. However, to get the date part only (without the time part), you use the double colons (::) to cast a DATETIME value to a DATE value. The result is in the format: yyyy-mm-dd .

How do I format date in PostgreSQL?

DATE data type in PostgreSQL is used to store dates in the YYYY-MM-DD format (e.g. 2022-03-24). It needs 4 bytes to store a date value in a column. Note that the earliest possible date is 4713 BC and the latest possible date is 5874897 AD. It is highly important to retain code readability at the stage of writing it.


1 Answers

A DATE column does not have a format. You cannot specify a format for it.

You can use DateStyle to control how PostgreSQL emits dates, but it's global and a bit limited.

Instead, you should use to_char to format the date when you query it, or format it in the client application. Like:

SELECT to_char("date", 'DD/MM/YYYY') FROM mytable; 

e.g.

regress=> SELECT to_char(DATE '2014-04-01', 'DD/MM/YYYY');   to_char    ------------  01/04/2014 (1 row) 
like image 140
Craig Ringer Avatar answered Sep 18 '22 16:09

Craig Ringer