Java计算时间差、日期差

时间:2025-03-10 08:42:49

在java中,计算时间差或日期差有多种方法,以下提供五种示例:


目录

一、使用 Instant 和 Duration 类计算时间差

二、使用 LocalDate 和 ChronoUnit 类计算日期差

三、使用 Joda-Time 库计算时间差和日期差

四、使用 Instant 和 Period 类计算日期差

五、使用 Java 8 的  类计算时间或日期差

Joda-Time


一、使用 Instant 和 Duration 类计算时间差

Instant start = ();
(1000);   // 让程序睡眠 1 秒钟,模拟耗时操作
Instant end = ();

Duration duration = (start, end);
("Time elapsed: " + () + " milliseconds");

这个示例使用 Instant 类获取开始时间和结束时间,然后使用 Duration 类计算时间差。Duration 类提供了一些方便的方法,如 toMillis() 和 toSeconds() 方法,可以将时间差转换为毫秒或秒数。

二、使用 LocalDate 和 ChronoUnit 类计算日期差

LocalDate start = (2021, , 1);
LocalDate end = (2021, , 31);

long days = (start, end);
("Days elapsed: " + days);

这个示例使用 LocalDate 类获取开始日期和结束日期,在使用 ChronoUnit 类计算日期差时,使用 DAYS 枚举表示计算出的日期差的时间单位为天数。需要注意的是,ChronoUnit 类提供了多个时间单位,可以根据具体需求选择适当的时间单位。

三、使用 Joda-Time 库计算时间差和日期差

DateTime start = new DateTime(2022, 1, 1, 0, 0, 0, 0);
DateTime end = new DateTime(2022, 12, 31, 23, 59, 59, 999);

Duration duration = new Duration(start, end);
("Time elapsed: " + () + " milliseconds");

Days days = ((), ());
("Days elapsed: " + ());

这个示例使用 Joda-Time 库获取开始时间和结束时间。在计算时间差时,使用 Duration 类计算时间差,并使用 getMillis() 方法获取时间差的毫秒数;在计算日期差时,使用 Days 类计算日期差,并使用 getDays() 方法获取天数。需要注意的是,该库已在 Java 8 中得到了标准化,因此,现在的 Java 版本已经可以通过使用  包来代替 Joda-Time 库。Joda-Time库的使用在文章末尾!

四、使用 Instant 和 Period 类计算日期差

Instant start = ();
(1000);   // 让程序睡眠 1 秒钟,模拟耗时操作
Instant end = ();

Period period = ((()).toLocalDate(),
                               (()).toLocalDate());
("Days elapsed: " + ());

这个示例使用 Instant 类获取开始时间和结束时间,并使用 Period 类计算日期差。Period 类用于以年、月和日为单位表示时间段。需要注意的是,由于 Instant 类表示一个瞬间,不包含时区和日期信息,因此,需要使用 atZone() 方法将其转换为带时区的 ZonedDateTime 类。如果程序运行在不同的时区中,需注意时区的差异对最终计算结果的影响。

五、使用 Java 8 的  类计算时间或日期差

LocalDateTime start = (2021, , 1, 0, 0, 0);
LocalDateTime end = (2021, , 31, 23, 59, 59);

long days = (start, end);
long hours = (start, end);
long minutes = (start, end);
long seconds = (start, end);

("Days elapsed: " + days);
("Hours elapsed: " + hours);
("Minutes elapsed: " + minutes);
("Seconds elapsed: " + seconds);

这个示例使用 Java 8 的  类获取开始时间和结束时间,然后计算时间或日期差。ChronoUnit 类提供了多个方法,可用于计算不同时间段的差。在使用此方法时,需要注意开始时间和结束时间必须是同一时间段的。

Joda-Time

maven

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.10</version>
</dependency>

 Joda-Time 库的通用工具类,主要包括日期、时间、时间间隔等功能

import .*;
import ;
import ;

public class JodaTimeUtils {

    // 获取当前日期
    public static LocalDate getCurrentDate() {
        return new LocalDate();
    }

    // 获取当前时间
    public static LocalTime getCurrentTime() {
        return new LocalTime();
    }

    // 获取当前日期和时间
    public static LocalDateTime getCurrentDateTime() {
        return new LocalDateTime();
    }

    // 获取指定日期的开始时间
    public static LocalDateTime getStartOfDay(LocalDate date) {
        return ();
    }

    // 获取指定日期的结束时间
    public static LocalDateTime getEndOfDay(LocalDate date) {
        return ();
    }

    // 获取指定日期时间的格式化字符串
    public static String formatDateTime(LocalDateTime dateTime, String pattern) {
        DateTimeFormatter formatter = (pattern);
        return (formatter);
    }

    // 将格式化字符串转换成日期时间
    public static LocalDateTime parseDateTime(String dateTimeString, String pattern) {
        DateTimeFormatter formatter = (pattern);
        return (dateTimeString);
    }

    // 计算两个日期之间的天数
    public static int getDaysBetween(LocalDate startDate, LocalDate endDate) {
        Days days = (startDate, endDate);
        return ();
    }

    // 计算两个日期时间之间的秒数
    public static int getSecondsBetween(LocalDateTime startDateTime, LocalDateTime endDateTime) {
        Seconds seconds = (startDateTime, endDateTime);
        return ();
    }

    // 计算两个日期时间之间的分钟数
    public static int getMinutesBetween(LocalDateTime startDateTime, LocalDateTime endDateTime) {
        Minutes minutes = (startDateTime, endDateTime);
        return ();
    }

    // 计算两个日期时间之间的小时数
    public static int getHoursBetween(LocalDateTime startDateTime, LocalDateTime endDateTime) {
        Hours hours = (startDateTime, endDateTime);
        return ();
    }

    // 计算两个日期时间之间的毫秒数
    public static long getMillisBetween(LocalDateTime startDateTime, LocalDateTime endDateTime) {
        return new Duration((), ()).getMillis();
    }

    // 判断两个日期是否相等
    public static boolean isEqual(LocalDate date1, LocalDate date2) {
        return (date2);
    }

    // 判断两个日期时间是否相等
    public static boolean isEqual(LocalDateTime dateTime1, LocalDateTime dateTime2) {
        return (dateTime2);
    }

    // 判断一个日期是否在另一个日期之前
    public static boolean isBefore(LocalDate date1, LocalDate date2) {
        return (date2);
    }

    // 判断一个日期时间是否在另一个日期时间之前
    public static boolean isBefore(LocalDateTime dateTime1, LocalDateTime dateTime2) {
        return (dateTime2);
    }

    // 判断一个日期是否在另一个日期之后
    public static boolean isAfter(LocalDate date1, LocalDate date2) {
        return (date2);
    }

    // 判断一个日期时间是否在另一个日期时间之后
    public static boolean isAfter(LocalDateTime dateTime1, LocalDateTime dateTime2) {
        return (dateTime2);
    }

    // 判断一个日期是否在另一时间间隔内
    public static boolean isInInterval(LocalDate date, Interval interval) {
        return (());
    }

    // 判断一个日期时间是否在另一时间间隔内
    public static boolean isInInterval(LocalDateTime dateTime, Interval interval) {
        return (());
    }
}

使用示例:

LocalDate date1 = new LocalDate(2020, 1, 1);
LocalDate date2 = new LocalDate(2022, 1, 1);
((date1, date2)); // 输出 731

LocalDateTime dateTime1 = new LocalDateTime(2020, 1, 1, 12, 0, 0);
LocalDateTime dateTime2 = new LocalDateTime(2022, 1, 1, 12, 0, 0);
((dateTime1, dateTime2)); // 输出 17520

String dateTimeString = "2020-01-01 12:00:00";
LocalDateTime dateTime = (dateTimeString, "yyyy-MM-dd HH:mm:ss");
((dateTime, "yyyy年MM月dd日 HH:mm:ss")); // 输出 2020年01月01日 12:00:00

LocalDateTime startDateTime = new LocalDateTime(2020, 1, 1, 12, 0, 0);
LocalDateTime endDateTime = new LocalDateTime(2022, 1, 1, 12, 0, 0);
Interval interval = new Interval((), ());

LocalDateTime dateTimeBefore = new LocalDateTime(2019, 1, 1, 12, 0, 0);
((dateTimeBefore, interval)); // 输出 false

LocalDateTime dateTimeAfter = new LocalDateTime(2023, 1, 1, 12, 0, 0);
((dateTimeAfter, interval)); // 输出 false

LocalDateTime dateTimeWithin = new LocalDateTime(2021, 1, 1, 12, 0, 0);
((dateTimeWithin, interval)); // 输出 true