【PostgreSQL】获取当前时间与时间类型转换

参考官方文档:
https://www.postgresql.org/docs/10/functions-formatting.html
https://www.postgresql.org/docs/10/functions-datetime.html

查询当前时间 Current Date/Time

PostgreSQL提供了许多函数,它们返回与当前日期和时间相关的值。这些SQL标准函数都基于当前事务的开始时间返回值:

时间相关值

select CURRENT_DATE
select CURRENT_TIME
select CURRENT_TIMESTAMP
select CURRENT_TIME(precision )
select CURRENT_TIMESTAMP(precision )
select LOCALTIME
select LOCALTIMESTAMP
select LOCALTIME(precision )
select LOCALTIMESTAMP(precision )
  • CURRENT_TIMECURRENT_TIMESTAMP是带时区的值;
  • LOCALTIMELOCALTIMESTAMP是不带时区的值。
  • precision是时间精度,传整型值,1代表毫秒保留1位,2代表毫秒保留2位

时间相关函数

select transaction_timestamp()
select statement_timestamp()
select clock_timestamp()
select timeofday()
select now()
  • transaction_timestamp()等效于CURRENT_TIMESTAMP
  • statement_timestamp()返回当前语句的开始时间(更具体地说,是从客户端收到最新命令消息的时间)。
  • statement_timestamp()transaction_timestamp()在事务的第一个命令期间返回相同的值,但在后续命令期间可能有所不同。
  • clock_timestamp()返回实际的当前时间,在单个SQL命令中,其值也会更改。
  • timeofday()是PostgreSQL的历史功能。像clock_timestamp()一样,它返回实际的当前时间,但以格式化的文本字符串的形式返回,而不是带有时区值的时间戳。
  • now()等效于transaction_timestamp()

时间类型转换的方法

PostgreSQL格式化功能提供了将各种数据类型(日期/时间,整数,浮点数,数字)转换为格式化字符串,以及从格式化字符串转换为特定数据类型。这些函数都遵循一个通用的调用约定:第一个参数是要格式化的值,第二个参数是定义输出或输入格式的模板。

Function Return Type Description Example
to_char(timestamp, text) text 将时间戳转换为字符串 to_char(current_timestamp,‘HH12:MI:SS’)
to_char(interval, text) text 将间隔转换为字符串 to_char(interval ‘15h 2m 12s’, ‘HH24:MI:SS’)
to_char(int, text) text 将整型数转换为字符串 to_char(125, ‘999’)
to_char(double precision, text) text 将实数/双精度转换为字符串 to_char(125.8::real, ‘999D9’)
to_char(numeric, text) text 将数字转换为字符串 to_char(-125.8, ‘999D99S’)
to_date(text, text) date 将字符串转换为日期 to_date(‘05 Dec 2000’, ‘DD Mon YYYY’)
to_number(text, text) numeric 将字符串转换为数字 to_number(‘12,454.8-’, ‘99G999D9S’)
to_timestamp(text, text) timestamp with time zone 将字符串转换为时间戳 to_timestamp(‘05 Dec 2000’, ‘DD Mon YYYY’)

你可能感兴趣的:(数据库,#,PostgreSQL,postgresql,后端,java,数据库)