Java Calendarクラスを使って年度を取得する方法
環境
Java SE 1.8
Eclipse 4.14.0
書式
1.カレンダーオブジェクトを取得
Calendar calendar = Calendar.getInstance()
年の取得
calendar.get(Calendar.YEAR)
2.StringからDateへ型変換
SimpleDateFormat sdf = new SimpleDateFormat(日付の形式);
Date day = sdf.parse(文字列);
使用例
package com.arkgame.study;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class ArkgDemo {
// 年月日の形式
private static final String DATE_FMT = "yyyy/MM/dd";
// 月の形式
private static final String MM_FMT = "MM";
public static void main(String[] args) {
// 年度を求める日付を設定
String cft = "2023/02/17";
try {
// StringからDateへ型変換
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FMT);
Date day = sdf.parse(cft);
// 年度を計算
int year = funA(day);
System.out.println("2023/02/17の年度: " + year);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 年度を返す
*
* @param date
* @return 年度
*/
static int funA(Date date) {
int year = 0;
SimpleDateFormat sdf = new SimpleDateFormat(MM_FMT);
// 月の取得
String dateStr = sdf.format(date);
// Stringからint型へ型変換
int month = Integer.parseInt(dateStr);
// カレンダーオブジェクトを取得
Calendar calendar = Calendar.getInstance();
// 時間の値をセット
calendar.setTime(date);
if (month < 4) {
// 1~3月の場合 西暦から-1する
calendar.add(Calendar.YEAR, -1);
// 年のみ取得
year = calendar.get(Calendar.YEAR);
} else {
// 4~12月の場合 年のみ取得
year = calendar.get(Calendar.YEAR);
}
return year;
}
}
実行結果
2023/02/17の年度: 2022