SAK 図書館
PostgreSQL 編14 - 日付関数、システム日付、切捨、日付差、日付加算、書式
■システム日付、システム時間
・current_timestamp() 関数は、システム日付(サーバ日付) を返す。
時間部分に秒以下がある。
select current_date;
date
------------
2002-11-03
select current_time;
timetz
--------------------
02:46:07.950125+09
select current_timestamp;
timestamptz
-------------------------------
2002-11-03 02:46:29.970125+09
select now();
now
-------------------------------
2002-11-03 02:53:21.060125+09
select to_char(current_timestamp, 'yyyy.mm.dd hh24:mi:ss');
to_char
---------------------
2002.11.03 02:47:17
■日付切り捨て
・date_trunc() 関数は、タイムスタンプを切り捨てる。
select date_trunc('hour', current_timestamp);
|_ year 年
month 月
day 日
dow 曜日(0 日曜)
hour 時
minute 分
second 秒
week 週
quarter 四半期
doy 年間通算日(うるう年は 366 日まで)
epoch 1970.01.01 からの通算秒
date_trunc
------------------------
2002-11-03 03:00:00+09
■日付の差 (日付間隔、日付範囲)
・PostgreSQL では、months_between() は使えない。
単純な四則演算で変換計算されるようである。
(日付計算、日数計算、カレンダー計算)
select current_timestamp -
to_timestamp('2002.11.01 00:00:00', 'yyyy.mm.dd hh24:mi:ss');
?column?
------------------------
2 days 02:56:21.136125
■日付の加算
・PostgreSQL では、add_months() は使えない。
(日付計算、日数計算、カレンダー計算)
select current_timestamp + 1;
?column?
------------
2002-11-04
select current_timestamp + '1 days';
■次の曜日
・PostgreSQL では、next_day() は使えない。
ストアド等で計算かな。
尚、曜日は date_part で求められる。
select date_part('dow', current_timestamp);
|_ 曜日(0 が日曜)
date_part
-----------
0
■月末日
・PostgreSQL では、last_day() は使えない。
ストアド等で計算かな。
■年齢、勤続
・age() 関数は、年齢や勤続を求めます。
select age(current_timestamp, '1958-01-26');
age
----------------------------------------
44 years 9 mons 8 days 03:46:33.548125
■日付型へ変換(書式変換、日付変換)
・to_date() 関数は、文字日付を日付型に変換します。
to_timestamp() 関数は、時間も含みます。(to_time はない。)
時間部分は、HH24:MI:SS 等の書式を使います。
Oracle の 「RR」書式は使えない。
select to_date('20010712', 'YYYYMMDD');
to_date
------------
2001-07-12
select to_timestamp('04:16:00', 'HH24:MI:SS');
to_timestamp
---------------------
0001-01-01 04:16 BC
select to_date('2001.07.12', 'YYYY.MM.DD');
select to_timestamp('2002.11.03 04:16:00', 'YYYY.MM.DD HH24:MI:SS');
to_timestamp
------------------------
2002-11-03 04:16:00+09
・5 日後を計算するなら、次のようにします。
select to_date('2001.07.12', 'YYYY.MM.DD') + 5;
?column?
------------
2001-07-17
・5 日後を計算して文字型にするなら、次のようにします。
select to_char(to_date('20010712', 'YYYYMMDD') + 5, 'yyyy/mm/dd');
to_char
------------
2001/07/17
select to_char(to_date('2001.07.12', 'YYYY.MM.DD') + 5, 'yyyy.mm.dd');
to_char
------------
2001.07.17
select to_char(to_date('01/07/12', 'RR/MM/DD') + 5, 'yy/mm/dd');
to_char
----------
00/07/17
・元もとが日付型なら、次のようになります。
select to_char(now() + 5, 'yyyy/mm/dd');
to_char
------------
2002/11/08
・曜日書式は、次のようになります。
select to_char(now(), 'yyyy.mm.dd Dy hh24:mi:ss');
to_char
-------------------------
2002.11.03 Sun 04:26:01
■型変換
・cast() 関数は、ANSI 規程の変換関数です。
select cast('99-01-01' as date);
date
------------
1999-01-01
■PostgreSQL 編、JAVA Servlet、JSP 編資料
■MySQL 編資料
■SQL 基礎編資料
■SQL 基礎実地編資料
■SQL チューニング編資料
■Oracle PL/SQL 編資料