string PostgreSQL:将字符串转换为日期 DD/MM/YYYY

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24301939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:19:05  来源:igfitidea点击:

PostgreSQL : cast string to date DD/MM/YYYY

stringpostgresqldatecasting

提问by wiltomap

I'm trying to cast a CHARACTER VARYINGcolumn to a DATEbut I need a date format like this : DD/MM/YYYY. I use the following SQLquery :

我正在尝试将一CHARACTER VARYING列转换为 aDATE但我需要这样的日期格式 : DD/MM/YYYY。我使用以下SQL查询:

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.

结果是这样的日期:YYYY-MM-DD

How can I get the DD/MM/YYYYformat ?

我怎样才能得到DD/MM/YYYY格式?

Thanks a lot in advance !

非常感谢!

Thomas

托马斯

回答by Craig Ringer

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

DATE列没有的格式。您不能为其指定格式。

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

您可以使用DateStyle来控制 PostgreSQL 发出日期的方式,但它是全局的,并且有一些限制。

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

相反,您应该to_char在查询时使用来格式化日期,或者在客户端应用程序中对其进行格式化。喜欢:

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)

回答by Vao Tsun

The documentationsays

文件说:

The output format of the date/time types can be set to one of the four styles ISO 8601, SQL (Ingres), traditional POSTGRES (Unix date format), or German. The default is the ISO format.

日期/时间类型的输出格式可以设置为 ISO 8601、SQL (Ingres)、传统 POSTGRES(Unix 日期格式)或德语四种样式之一。默认为 ISO 格式。

So this particular format can be controlled with postgresdate time output, eg:

所以这个特殊的格式可以用postgres日期时间输出来控制,例如:

t=# select now();
              now
-------------------------------
 2017-11-29 09:15:25.348342+00
(1 row)

t=# set datestyle to DMY, SQL;
SET
t=# select now();
              now
-------------------------------
 29/11/2017 09:15:31.28477 UTC
(1 row)

t=# select now()::date;
    now
------------
 29/11/2017
(1 row)

Mind that as @Craig mentioned in his answer, changing datestylewill also (and in first turn) change the way postgres parses date.

请注意,正如@Craig 在他的回答中提到的,更改datestyle也将(并且首先)更改 postgres 解析日期的方式。