2
3

More than 3 years have passed since last update.

【Java】Calendarクラスの使い方

Posted at

プログラミング勉強日記

2020年10月29日
JavaでCalendarクラスを扱ったので使い方を簡単にまとめる。

Calendarクラスとは

 日付や指定した年月日時の操作を行うためのクラス。Javaで日時の計算や取得、設定をするために使う。

 Calendarクラスでは演算子newではなく、getInstanceメソッドを呼ぶことでオブジェクトを生成する。getInstanceメソッドは呼び出すごとに現在の日付と時間に初期化された状態でオブジェクトを返す。使用するときは、必ずimport java.util.Calendarを指定する。

サンプルコード

import java.util.Calendar

public class Main {
  public static void main(String[] args) throws Exception {
    Calendar calendar = Calendar.getInstance();
    System.out.println(calendar.get(Calendar.YEAR) + "年" + calendar.get(Calendar.MONTH)+ "月" + calendar.get(Calendar.DATE) + "日" );
  }
}
実行結果
2020年10月29日

基本的なメソッドの使い方

setメソッド

 setメソッドは日時を設定するために使う。なので、日付を処理するプログラムでよく使われている。

 以下の例では指定した要素(今回だと年数)以外は前の値のままになるので注意する。

使い方
import java.util.Calendar

public class Main {
  public static void main(String[] args) throws Exception {
    Calendar calendar = Calendar.getInstance();
    System.out.println("現在日時:" + calendar.getTime().toString());

    // 年を2022年に設定する
    calendar.set(Calendar.YEAR, 2022);
    System.out.println("年に2022年を設定:" + calendar.getTime());
  }
}
実行結果
現在日時:Thu Oct 29 10:43:58 UTC 2020
年に2022年を設定:Thu Oct 29 10:43:58 UTC 2022

addメソッド

 Calendarクラスで日付の加減算を行うときにはaddメソッドを使用する。

使い方
import java.util.Calendar

public class Main {
  public static void main(String[] args) throws Exception {
    Calendar calendar = Calendar.getInstance();
    System.out.println("現在日時:" + calendar.getTime().toString());

    // 年を1加算する
    calendar.add(Calendar.YEAR, 1);
    System.out.println("1年増やす:" + calendae.getTime());
  }
}
実行結果
現在日時:Thu Oct 29 10:43:58 UTC 2020
1年増やす:Thu Oct 29 10:43:58 UTC 2021

formatメソッド

 文字列で日付のフォーマットを指定することができる。

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

public class Main {
  public static void main(String[] args) {
     Calendar calendar = Calendar.getInstance();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
    System.out.println(sdf.format(calendar.getTime())); 
  }
}
実行結果
2020年10月20日

参考文献

【Java】日時の計算や取得に使えるCalendarクラスの使い方!
【Java入門】Calendarクラスの使い方を完全解説(set/add/format)
【Java入門】Calendarの日付フォーマットを指定する(format)
【Java入門】Calendarの使い方(add)

2
3
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
2
3