1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaで日付差・時間差を計算するときの ChronoUnit / Period / Duration の違い

Last updated at Posted at 2025-10-25

Java 8 以降、日付や時間を扱うときは java.time パッケージを使うのが一般的です。
よく使うのが以下の3つ:
ChronoUnit:単位ベースで差を計算
Period:年月日単位で差を計算
Duration:時間ベースで差を計算
この記事では 挙動の違い と 使いどころ を整理します。

  1. ChronoUnit(DAYSなど)
    分類:日付ベース(date-based unit)
    特徴:
    暦上の日単位を表す
    LocalDate または LocalDateTime で使用可能
    24時間経過していない場合は 0 日になる
    用途:シンプルに日数差を計算したいとき

'''java -
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class ChronoUnitExample {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2024,10,1);
LocalDate end = LocalDate.of(2024,10,25);
System.out.println(ChronoUnit.DAYS.between(start, end)); // 24

    LocalDateTime t1 = LocalDateTime.of(2024,10,1,23,0);
    LocalDateTime t2 = LocalDateTime.of(2024,10,2,1,0);
    System.out.println(ChronoUnit.DAYS.between(t1, t2)); // 0(24時間未満)
}

}
'''

  1. Period(年月日単位)
    分類:日付ベース(date-based)
    特徴:
    年・月・日単位で差を表現できる
    時間やタイムゾーンは無視
    総日数ではなく「残り日」のみを返すことに注意
    用途:契約期間や生年月日など、年月日で差分を管理したいとき

'''java
import java.time.LocalDate;
import java.time.Period;

public class PeriodExample {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2024,1,1);
LocalDate end = LocalDate.of(2025,3,4);

    Period p = Period.between(start, end);
    System.out.println(p); // P1Y2M3D (1年2か月3日)
    System.out.println(p.getDays()); // 3
}

}
'''

  1. Duration(時間ベース)
    分類:時間ベース(time-based unit)
    特徴:
    秒・ナノ秒単位で正確に経過時間を表現
    LocalDateTime / Instant に使用
    24時間未満でも経過時間を計測できる
    用途:イベントの実経過時間、タイマー、ログ計測など
    '''java
    import java.time.Duration;
    import java.time.LocalDateTime;

public class DurationExample {
public static void main(String[] args) {
LocalDateTime t1 = LocalDateTime.of(2024,10,1,23,0);
LocalDateTime t2 = LocalDateTime.of(2024,10,2,1,0);

    Duration d = Duration.between(t1, t2);
    System.out.println(d.toHours());   // 2
    System.out.println(d.toMinutes()); // 120
}

}
'''

  1. まとめ(比較表)
    | クラス/単位 | ベース | 特徴 | 結果例 | 用途 |
    | ----------------- | ----- | ---------- | ------------- | ------------ |
    | ChronoUnit.DAYS | 日付ベース | 24時間単位で丸め | 0日 / 1日 / 24日 | 日数差(簡易) |
    | Period | 日付ベース | 年・月・日単位で差分 | P1Y2M3D | 契約期間・年月日計算 |
    | Duration | 時間ベース | 秒・ナノ秒単位で正確 | 2時間 / 120分 | 実経過時間、タイマー計測 |
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?