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
PostgreSQL : cast string to date DD/MM/YYYY
提问by wiltomap
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 :
我正在尝试将一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/YYYY
format ?
我怎样才能得到DD/MM/YYYY
格式?
Thanks a lot in advance !
非常感谢!
Thomas
托马斯
回答by Craig Ringer
A DATE
column does not have a format. You cannot specify a format for it.
一DATE
列没有的格式。您不能为其指定格式。
You can use DateStyle
to control how PostgreSQL emits dates, but it's global and a bit limited.
您可以使用DateStyle
来控制 PostgreSQL 发出日期的方式,但它是全局的,并且有一些限制。
Instead, you should use to_char
to 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 postgres
date 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 datestyle
will also (and in first turn) change the way postgres parses date.
请注意,正如@Craig 在他的回答中提到的,更改datestyle
也将(并且首先)更改 postgres 解析日期的方式。