😺

【Java】java.time.Periodクラスの例

2025/01/27に公開

サマータイムやうるう年なども考慮しながら日数ベースで期間を管理する必要がある場合に使用

between

2つの LocalDate の間の期間を求める例

public class BetweenTest {
	public static void main(String[] args) {
		LocalDate startDate = LocalDate.of(2023, 1, 1); // 開始日
		LocalDate endDate = LocalDate.of(2024, 1, 1); // 終了日

		Period period = Period.between(startDate, endDate); // 期間を計算
		System.out.println("期間: " + period.getYears() + "年 " + period.getMonths() + "ヶ月 " + period.getDays() + "日");
	}
}

of

指定した年、月、日を使って期間を作成

public class OfTest {
	public static void main(String[] args) {
		Period period = Period.of(2, 3, 10); // 2年3ヶ月10日の期間を作成
		System.out.println("期間: " + period.getYears() + "年 " + period.getMonths() + "ヶ月 " + period.getDays() + "日");
	}
}

getDays

Period に含まれる日数を取得

public class GetDaysTest {
	public static void main(String[] args) {
		Period period = Period.of(1, 2, 15); // 1年2ヶ月15日
		System.out.println("日数: " + period.getDays());
	}
}

getMonths

Period インスタンスに含まれる月数を取得

public class GetMonths {
	public static void main(String[] args) {
		Period period = Period.of(1, 2, 15); // 1年2ヶ月15日
		System.out.println("月数: " + period.getMonths());
	}
}

getYears

Period インスタンスから指定した年数分を減算

public class MinusYearsTest {
	public static void main(String[] args) {
		Period period = Period.of(3, 6, 10); // 3年6ヶ月10日
		Period newPeriod = period.minusYears(1); // 1年を引く
		int years = newPeriod.getYears();
		int months = newPeriod.getMonths();
		int days = newPeriod.getDays();

		System.out.println("減算後の期間: " + years + "年 " + months + "ヶ月 " + days + "日");
	}
}

plusMonth

Period から指定した年数を減算

public class PlusMonthsTest {
	public static void main(String[] args) {
		Period period = Period.of(1, 3, 5); // 1年3ヶ月5日
		Period newPeriod = period.plusMonths(4); // 4ヶ月を加算
		int years = newPeriod.getYears();
		int months = newPeriod.getMonths();
		int days = newPeriod.getDays();

		System.out.println("加算後の期間: " + years + "年 " + months + "ヶ月 " + days + "日");
	}
}

toTotalMonths

Period インスタンスを月数の合計として返します。年数と月数を月単位に換算し、全体の月数を算出

public class ToTotalMonthsTest {
	public static void main(String[] args) {
		Period period = Period.of(2, 5, 10); // 2年5ヶ月10日
		long totalMonths = period.toTotalMonths(); // 合計月数
		System.out.println("合計月数: " + totalMonths);
	}
}

Udemyで講座を公開中!
https://zenn.dev/codek2/articles/e9e44f3e0023fb

X(旧Twitter)
https://twitter.com/kunchan2_

Zenn 本
https://zenn.dev/codek2?tab=books

Youtube
https://www.youtube.com/@codek2_studio

Discussion