在PostgreSQL中使用日期類型時一些需要注意的地方,postgresql日期

來源:互聯網
上載者:User

在PostgreSQL中使用日期類型時一些需要注意的地方,postgresql日期

 當我們這些使用Rails的人看到例如5.weeks.from_nowor3.days.ago + 2.hours時並不會感到驚訝。同樣,PostgreSQL也可以做到,你可以通過簡單調用PostgreSQL內建函數來實現相同的功能。
目前時間/日期/時間戳

擷取目前時間的方式有很多種,在這之前我們需要知道以下兩種類型的區別:

  •     總是返回當前的值 (clock_timestamp())
  •     總是返回當前值,但在事務中它返回的是事務開始的時間(now())

讓我們看下面這個例子
 

postgres=# BEGIN;postgres=# SELECT now();       now------------------------------- 2013-08-26 12:17:43.182331+02 postgres=# SELECT now();       now------------------------------- 2013-08-26 12:17:43.182331+02 postgres=# SELECT clock_timestamp();    clock_timestamp------------------------------- 2013-08-26 12:17:50.698413+02 postgres=# SELECT clock_timestamp();    clock_timestamp------------------------------- 2013-08-26 12:17:51.123905+02

你會發現,語句執行時候clock_timestamp()的傳回值每次都發生了改變,但是now()總是返回相同的值。當你需要考慮時區時,你應該特別注意這兩個函數差異。

時間區間:比如3天前

使用interval操作符你可以輕鬆的構建一個時間區間,例如

  •     interval '1 day'
  •     interval '5 days'
  •     interval '5 days' + interval '3 hours'
  •     interval '5 days 3 hours'

你可以看到,我們可以用interval操作符來簡單的進行數學運算,這特別適合於構建例如3天前這樣的時間區間,比如:
 

postgres=# SELECT now() - interval '3 days';      ?column?------------------------------- 2013-08-23 12:23:40.069717+02

擷取星期幾

有些時候對於一個給定的時間,你僅僅只想知道的是這天是星期幾或者是它屬於那個世紀的更或者你只想知道它是一年中的第幾天。PostgreSQL中的extract()函數提供了這種功能。

如下例子是在8月26日 星期一進行測試的。
 

postgres=# SELECT extract(DAY FROM now()); date_part-----------    26 postgres=# SELECT extract(DOW FROM now()); date_part-----------     1

extract()還有其他更強大的功能,詳情請參閱官方文檔,在這裡只列舉了一小部分:

  •     day
  •     century
  •     dow(day of week)
  •     doy(day of year)
  •     minute
  •     month
  •     year


時區轉換

有些時候,時區轉換對於特定時間在不同時區顯示特別有用。AT TIME ZONE提供了這種功能,它是如何做到的?我們將在一個事務中進行示範,因為同一事務中now()函數總是返回相同的值,從而我們可以很容易看到同一時間在不同時區顯示的差別。
 

postgres=# BEGIN;BEGINpostgres=# SELECT now();       now------------------------------- 2013-08-26 12:39:39.122218+02 postgres=# SELECT now() AT TIME ZONE 'GMT';     timezone---------------------------- 2013-08-26 10:39:39.122218 postgres=# SELECT now() AT TIME ZONE 'GMT+1';     timezone---------------------------- 2013-08-26 09:39:39.122218 postgres=# SELECT now() AT TIME ZONE 'PST';     timezone---------------------------- 2013-08-26 02:39:39.122218

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.