3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaのDateクラスのコンストラクタを使うと、日付が1900年進む現象

Last updated at Posted at 2018-06-06

すごく今更感があることですが、地味にハマってしまいました…。

はじめに

日付を文字列にフォーマットするプログラムを書いていたところ、なぜか年数が1900年進んてしまう現象に遭遇しました。そもそもDateクラスの「年、月、日」をとるコンストラクタは非推奨なので、確かに使わなければ済む話ではあります。しかし、それを知らずにうっかり使うとこうなる、という失敗の一例です。

#現象

DateTest.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {
  public static void main(String[] args) {
    int year = 2018;
    int month = 5;
    int dayOfMonth = 6;
    Date todayDate = new Date(year, month, dayOfMonth);
    DateFormat dateFormat = SimpleDateFormat.getDateInstance();
    System.out.println(dateFormat.format(todayDate));
  }
}

この例のように、int型で与えられた年月日を元にDateインスタンスを生成し、それをDateFormatFormatすると、

3918/06/06

今年は2018年なのに、3918年となっています。ちょうど1900年進んでいます。

#理由
これは、java.util.Dateクラスの仕様です。
Date (Java Platform SE 8) にも書いてあるのですが、このコンストラクタで受け取るyearの値は、西暦年から1900を引いた値をとる、という実装になっています。

#そもそも…
詳しい方にとっては周知の事実なのですが、java.util.Dateの年月日を取るコンストラクタは、JDK1.1から非推奨となっています(Dateで検索すると出てくるので、つい使いそうになりますが)。代わりに、java.util.Calendarでインスタンス化したのち、Calendar#getDateDateインスタンスを得たほうがよいでしょう。

DateTest.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DateTest {
  public static void main(String[] args) {
    int year = 2018;
    int month = 5;
    int dayOfMonth = 6;
    Calendar todayDate = Calendar.getInstance();
    todayDate.set(year, month, dayOfMonth);
    DateFormat dateFormat = SimpleDateFormat.getDateInstance();
    System.out.println(dateFormat.format(todayDate.getTime()));
  }
}

2018/07/06

これで、正常に日付が出力されるようになりました。

3
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?