LoginSignup
1
0

More than 5 years have passed since last update.

年度を多用する場合の考え方

Last updated at Posted at 2018-12-13

年度を使用するにあたって多いコード

public int getNendo(Date date){
    //1月~3月なら
    ...
    //4月~12月なら
    ...
}

こんなコードをよく見る。
考え方だけメモ。
必要な月数分ずらしたカレンダーみたいなものを用意して、そのカレンダー上、与えたDateが属する年を返却してくれれば良いのではないか。
(そういうカレンダークラスがあればなあ・・・)
余裕があったら作りたい。

追記

import java.util.Calendar;
import java.util.Date;

public class CustomCalendar {
    private int startMonth;

    public CustomCalendar(int startMonth) {
        if (startMonth < 1 || 12 < startMonth) {
            throw new IllegalArgumentException("開始月は1~12を指定してください。");
        }
        this.startMonth = startMonth;
    }

    public int getNend(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1 * (startMonth));
        return calendar.get(Calendar.YEAR);
    }

    public static int getNend(int startMonth, Date date) {
        CustomCalendar cal = new CustomCalendar(startMonth);
        return cal.getNend(date);
    }

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        for (int nendStart = 1; nendStart <= 12; nendStart++) {
            for (int dateMonth = 1; dateMonth <= 12; dateMonth++) {
                cal.set(2018, dateMonth, 1);
                int nend = CustomCalendar.getNend(nendStart, cal.getTime());
                System.out.println(String.format("年度開始月:%2d、カレンダーの月:%2dの場合、年度は%d", nendStart, dateMonth, nend));
            }
            System.out.println();
        }
    }
}

こんなもんでどうだろうか

1
0
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
1
0