Javaで月数を計算(カウント)する方法
表題の通り、Javaで月数を計算するプログラムを書いてみました。
1/1~1/31を1か月とカウントしたり、1/15~など中日から始まっても計算できるものを目指しました。
public class MonthDiff { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ testCountMonth("2021/01/01", "2021/01/30"); testCountMonth("2021/01/01", "2021/01/31"); testCountMonth("2021/01/01", "2021/02/01"); testCountMonth("2021/01/01", "2021/02/28"); testCountMonth("2021/01/01", "2021/03/01"); testCountMonth("2021/01/01", "2021/03/31"); // TODO 以下はどうなる? testCountMonth("2021/01/15", "2021/01/31"); testCountMonth("2021/01/15", "2021/02/01"); testCountMonth("2021/01/15", "2021/02/13"); testCountMonth("2021/01/15", "2021/02/14"); testCountMonth("2021/01/15", "2021/02/15"); testCountMonth("2021/01/15", "2021/02/16"); testCountMonth("2021/02/15", "2021/03/13"); testCountMonth("2021/02/15", "2021/03/14"); testCountMonth("2021/02/15", "2021/03/15"); testCountMonth("2021/02/15", "2021/03/16"); testCountMonth("2020/01/01", "2020/02/01"); testCountMonth("2020/01/01", "2020/02/28"); testCountMonth("2020/01/01", "2020/02/29"); testCountMonth("2020/01/01", "2020/03/01"); testCountMonth("2020/12/01", "2020/12/30"); testCountMonth("2020/12/01", "2020/12/31"); testCountMonth("2020/12/01", "2021/01/01"); } private static void testCountMonth(String strFromDate, String strToDate) { System.out.println(strFromDate + "-" + strToDate + " 月数:" + countMonths(strFromDate, strToDate)); } private static long countMonths(String strFromDate, String strToDate) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); LocalDate dtFromDate = LocalDate.parse(strFromDate, formatter); // 終了日に1日加算 LocalDate dtToDate = LocalDate.parse(strToDate, formatter); dtToDate = dtToDate.plusDays(1); Period period = Period.between(dtFromDate, dtToDate); return period.toTotalMonths(); // 以下は、1/15~2/1が1か月とカウントされた // YearMonth fromYM = YearMonth.parse(strFromDate, formatter); // YearMonth toYM = YearMonth.from(dt); //return ChronoUnit.MONTHS.between(fromYM, toYM); } }
実行結果
2021/01/01-2021/01/30 月数:0 2021/01/01-2021/01/31 月数:1 2021/01/01-2021/02/01 月数:1 2021/01/01-2021/02/28 月数:2 2021/01/01-2021/03/01 月数:2 2021/01/01-2021/03/31 月数:3 2021/01/15-2021/01/31 月数:0 2021/01/15-2021/02/01 月数:0 2021/01/15-2021/02/13 月数:0 2021/01/15-2021/02/14 月数:1 2021/01/15-2021/02/15 月数:1 2021/01/15-2021/02/16 月数:1 2021/02/15-2021/03/13 月数:0 2021/02/15-2021/03/14 月数:1 2021/02/15-2021/03/15 月数:1 2021/02/15-2021/03/16 月数:1 2020/01/01-2020/02/01 月数:1 2020/01/01-2020/02/28 月数:1 2020/01/01-2020/02/29 月数:2 2020/01/01-2020/03/01 月数:2 2020/12/01-2020/12/30 月数:0 2020/12/01-2020/12/31 月数:1 2020/12/01-2021/01/01 月数:1