日付の計算 (2/29 + 1年 – 1年 = 2/28)

システム開発で日付の処理で厄介なうるう年ですが、2/29は、1年足して、1年引くと違う日になっちゃうんですね。

import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) throws Exception {
Date d = DateFormat.getInstance().parse("2004/02/29 00:00:00");
Calendar c = Calendar.getInstance();
c.setTime(d);
System.out.println("org: " +
new SimpleDateFormat("yyyy/MM/dd").format(c.getTime()));
c.add(Calendar.YEAR, 1);
System.out.println(" +1: " +
new SimpleDateFormat("yyyy/MM/dd").format(c.getTime()));
c.add(Calendar.YEAR, -1);
System.out.println(" -1: " +
new SimpleDateFormat("yyyy/MM/dd").format(c.getTime()));
}
}
org: 2004/02/29
+1: 2005/02/28
-1: 2004/02/28

PostgreSQLでも、同じ。

postgres=# select
postgres-#  cast(
postgres(#    (cast('2004/02/29' as timestamp) + '1 year') as timestamp
postgres(#  ) + '-1 year' as leap;
leap
---------------------
2004-02-28 00:00:00
(1 行)

当たり前って言えば、あたりまえか。

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です


The reCAPTCHA verification period has expired. Please reload the page.

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください