LoginSignup
4
4

More than 5 years have passed since last update.

Javaで月ごと集計する際の最終日を算出する方法

Posted at

Javaで月ごとの集計をする際の「月ごと」を計算する上での範囲指定方法です。

月初は簡単。指定年月以外の初期化は、日だけ1、それ以外は0で初期化すればOK。

        Calendar calendar = Calendar.getInstance();
        //指定年, 指定月, 1日, 0時0分0秒
        calendar.set(year, month, 1, 0, 0, 0);
        //きっちりミリ秒も0にする
        calendar.set(Calendar.MILLISECOND, 0);

月末の範囲指定は、指定方法が2つあります。そのうち少々複雑な方を紹介します。
少々複雑ですが、考え方が分かれば難しいことはありません。
「指定月の翌月1日から1ミリ秒を引くと当月末になる」という方法です。

    public static Date getEndOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        //指定年, 指定月, 1日, 0時0分0秒
        calendar.set(year, month, 1, 0, 0, 0);
        //翌月にする (年またぎ対応)
        calendar.add(Calendar.MONTH, 1);
        //0時0分0秒0ミリ秒 - 1ミリ秒で、月末23時59分59秒999ミリ秒にできる
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.MILLISECOND, -1);
        return calendar.getTime();
    }

翌月1日未満、という簡単な指定が出来ればそちらを採用するべきだと思います。しかし、SQLで日付の条件にbetweenを使う場合には、今回した方法を使うことになるでしょう。

4
4
0

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
4
4