📜  java 8 datediff in days - Java (1)

📅  最后修改于: 2023-12-03 15:15:54.769000             🧑  作者: Mango

Java 8中的日期差

Java 8引入了新的日期时间API,提供了一种更简单的方式来处理日期和时间。日期差的计算很常见,许多开发人员想要知道如何在Java 8中计算日期差。

计算日期差的方式

Java 8中计算日期差有许多方法,以下是其中一些常用的方法:

使用Duration

Duration类用于表示时间间隔。我们可以使用Duration.between()方法来计算两个日期之间的时间间隔。以下是计算两个日期之间的天数差的示例代码:

LocalDate startDate = LocalDate.of(2020, 1, 1);
LocalDate endDate = LocalDate.of(2020, 1, 10);

Duration duration = Duration.between(startDate.atStartOfDay(), endDate.atStartOfDay());
long diff = duration.toDays();
System.out.println("Days between two dates: " + diff);
使用ChronoUnit.DAYS

我们还可以使用ChronoUnit类中的DAYS枚举值来计算两个日期之间的天数差。以下是示例代码:

LocalDate startDate = LocalDate.of(2020, 1, 1);
LocalDate endDate = LocalDate.of(2020, 1, 10);

long diff = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("Days between two dates: " + diff);
示例代码

以下是一个完整的Java 8示例程序,用于计算两个日期之间的天数差:

import java.time.Duration;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class DateDiff {

    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2020, 1, 1);
        LocalDate endDate = LocalDate.of(2020, 1, 10);

        // using Duration
        Duration duration = Duration.between(startDate.atStartOfDay(), endDate.atStartOfDay());
        long diff1 = duration.toDays();

        // using ChronoUnit.DAYS
        long diff2 = ChronoUnit.DAYS.between(startDate, endDate);

        System.out.println("Days between two dates using Duration: " + diff1);
        System.out.println("Days between two dates using ChronoUnit.DAYS: " + diff2);
    }

}

输出:

Days between two dates using Duration: 9
Days between two dates using ChronoUnit.DAYS: 9
总结

Java 8提供了多种计算日期差的方法,包括使用Duration类和ChronoUnit.DAYS枚举值。无论您选择哪种方法,都可以使用Java 8的新日期时间API轻松计算日期差。