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


目录

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

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

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

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

五、使用 Java 8 的 java.time.temporal.ChronoUnit 类计算时间或日期差

Joda-Time


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

Instant start = Instant.now();
Thread.sleep(1000);   // 让程序睡眠 1 秒钟,模拟耗时操作
Instant end = Instant.now();Duration duration = Duration.between(start, end);
System.out.println("Time elapsed: " + duration.toMillis() + " milliseconds");

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

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

LocalDate start = LocalDate.of(2021, Month.JANUARY, 1);
LocalDate end = LocalDate.of(2021, Month.DECEMBER, 31);long days = ChronoUnit.DAYS.between(start, end);
System.out.println("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);
System.out.println("Time elapsed: " + duration.getMillis() + " milliseconds");Days days = Days.daysBetween(start.toLocalDate(), end.toLocalDate());
System.out.println("Days elapsed: " + days.getDays());

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

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

Instant start = Instant.now();
Thread.sleep(1000);   // 让程序睡眠 1 秒钟,模拟耗时操作
Instant end = Instant.now();Period period = Period.between(start.atZone(ZoneId.systemDefault()).toLocalDate(),end.atZone(ZoneId.systemDefault()).toLocalDate());
System.out.println("Days elapsed: " + period.getDays());

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

五、使用 Java 8 的 java.time.temporal.ChronoUnit 类计算时间或日期差

LocalDateTime start = LocalDateTime.of(2021, Month.JANUARY, 1, 0, 0, 0);
LocalDateTime end = LocalDateTime.of(2021, Month.DECEMBER, 31, 23, 59, 59);long days = ChronoUnit.DAYS.between(start, end);
long hours = ChronoUnit.HOURS.between(start, end);
long minutes = ChronoUnit.MINUTES.between(start, end);
long seconds = ChronoUnit.SECONDS.between(start, end);System.out.println("Days elapsed: " + days);
System.out.println("Hours elapsed: " + hours);
System.out.println("Minutes elapsed: " + minutes);
System.out.println("Seconds elapsed: " + seconds);

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

Joda-Time

maven

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

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

import org.joda.time.*;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;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 date.toLocalDateTime(LocalTime.MIN);}// 获取指定日期的结束时间public static LocalDateTime getEndOfDay(LocalDate date) {return date.toLocalDateTime(LocalTime.MAX);}// 获取指定日期时间的格式化字符串public static String formatDateTime(LocalDateTime dateTime, String pattern) {DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);return dateTime.toString(formatter);}// 将格式化字符串转换成日期时间public static LocalDateTime parseDateTime(String dateTimeString, String pattern) {DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);return formatter.parseLocalDateTime(dateTimeString);}// 计算两个日期之间的天数public static int getDaysBetween(LocalDate startDate, LocalDate endDate) {Days days = Days.daysBetween(startDate, endDate);return days.getDays();}// 计算两个日期时间之间的秒数public static int getSecondsBetween(LocalDateTime startDateTime, LocalDateTime endDateTime) {Seconds seconds = Seconds.secondsBetween(startDateTime, endDateTime);return seconds.getSeconds();}// 计算两个日期时间之间的分钟数public static int getMinutesBetween(LocalDateTime startDateTime, LocalDateTime endDateTime) {Minutes minutes = Minutes.minutesBetween(startDateTime, endDateTime);return minutes.getMinutes();}// 计算两个日期时间之间的小时数public static int getHoursBetween(LocalDateTime startDateTime, LocalDateTime endDateTime) {Hours hours = Hours.hoursBetween(startDateTime, endDateTime);return hours.getHours();}// 计算两个日期时间之间的毫秒数public static long getMillisBetween(LocalDateTime startDateTime, LocalDateTime endDateTime) {return new Duration(startDateTime.toDateTime(), endDateTime.toDateTime()).getMillis();}// 判断两个日期是否相等public static boolean isEqual(LocalDate date1, LocalDate date2) {return date1.equals(date2);}// 判断两个日期时间是否相等public static boolean isEqual(LocalDateTime dateTime1, LocalDateTime dateTime2) {return dateTime1.equals(dateTime2);}// 判断一个日期是否在另一个日期之前public static boolean isBefore(LocalDate date1, LocalDate date2) {return date1.isBefore(date2);}// 判断一个日期时间是否在另一个日期时间之前public static boolean isBefore(LocalDateTime dateTime1, LocalDateTime dateTime2) {return dateTime1.isBefore(dateTime2);}// 判断一个日期是否在另一个日期之后public static boolean isAfter(LocalDate date1, LocalDate date2) {return date1.isAfter(date2);}// 判断一个日期时间是否在另一个日期时间之后public static boolean isAfter(LocalDateTime dateTime1, LocalDateTime dateTime2) {return dateTime1.isAfter(dateTime2);}// 判断一个日期是否在另一时间间隔内public static boolean isInInterval(LocalDate date, Interval interval) {return interval.contains(date.toDateTimeAtStartOfDay());}// 判断一个日期时间是否在另一时间间隔内public static boolean isInInterval(LocalDateTime dateTime, Interval interval) {return interval.contains(dateTime.toDateTime());}
}

使用示例:

LocalDate date1 = new LocalDate(2020, 1, 1);
LocalDate date2 = new LocalDate(2022, 1, 1);
System.out.println(JodaTimeUtils.getDaysBetween(date1, date2)); // 输出 731LocalDateTime dateTime1 = new LocalDateTime(2020, 1, 1, 12, 0, 0);
LocalDateTime dateTime2 = new LocalDateTime(2022, 1, 1, 12, 0, 0);
System.out.println(JodaTimeUtils.getHoursBetween(dateTime1, dateTime2)); // 输出 17520String dateTimeString = "2020-01-01 12:00:00";
LocalDateTime dateTime = JodaTimeUtils.parseDateTime(dateTimeString, "yyyy-MM-dd HH:mm:ss");
System.out.println(JodaTimeUtils.formatDateTime(dateTime, "yyyy年MM月dd日 HH:mm:ss")); // 输出 2020年01月01日 12:00:00LocalDateTime startDateTime = new LocalDateTime(2020, 1, 1, 12, 0, 0);
LocalDateTime endDateTime = new LocalDateTime(2022, 1, 1, 12, 0, 0);
Interval interval = new Interval(startDateTime.toDateTime(), endDateTime.toDateTime());LocalDateTime dateTimeBefore = new LocalDateTime(2019, 1, 1, 12, 0, 0);
System.out.println(JodaTimeUtils.isInInterval(dateTimeBefore, interval)); // 输出 falseLocalDateTime dateTimeAfter = new LocalDateTime(2023, 1, 1, 12, 0, 0);
System.out.println(JodaTimeUtils.isInInterval(dateTimeAfter, interval)); // 输出 falseLocalDateTime dateTimeWithin = new LocalDateTime(2021, 1, 1, 12, 0, 0);
System.out.println(JodaTimeUtils.isInInterval(dateTimeWithin, interval)); // 输出 true

Java计算时间差、日期差相关推荐

  1. JAVA--java计算时间差,日期差小结

    求两个时间值之间相差几分钟 public static void main(String[] args) throws Exception {SimpleDateFormat df = new Sim ...

  2. Java计算时间差、日期差总结(亲测)

    Java计算时间差.日期差总结 最近工作中遇到需要计算时间差,搜索了几种计算时间差的方法,这里总结一下 1.java 7中的日历类Calendar Calendar类使用其静态的getInstance ...

  3. Java计算时间差、日期差总结

    Java计算时间差.日期差总结 最近工作中遇到需要计算时间差,搜索了几种计算时间差的方法,这里总结一下 1.java 7中的日历类Calendar Calendar类使用其静态的getInstance ...

  4. Java 计算时间差

    Java 计算时间差 1. Date 计算时间差 2. 两 LocalDate 相差年份,返回Integer类型 3. LocalDateTime 计算时间差 1. Date 计算时间差 import ...

  5. java计算时间差_java中计算两个时间差

    java计算时间差及比较时间大小 比如:现在是2004-03-26 13:31:40 过去是:2004-01-02 11:30:24 我现在要获得两个日期差,差的形式为:XX天XX小时XX分XX秒 方 ...

  6. Java计算时间差_传统的SimpleDateFormat类

    Java计算时间差_传统的SimpleDateFormat类 SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd ...

  7. java 算出下一个工作日,Java:计算一个日期加下指定工作日数(排除周六周日和一系列节日)...

    Java:计算一个日期加上指定工作日数(排除周六周日和一系列节日) 工作时遇到的,随便写了个,欢迎高手点评: 核心代码: package www.sjjjob.com.date; import jav ...

  8. java计算指定日期的上个月

    文章目录 java计算指定日期的上个月 Calendar类 API 代码实现 java计算指定日期的上个月 Calendar类 Calendar类是一个抽象类,可以为在某一特定时刻和一组之间的转换的方 ...

  9. java计算时间差 Java问题通用解决代码

    java实现计算时间差 正式版:       /**        * 计算时间差,求出两者相隔的时间        *        * @param nowDate        *        ...

最新文章

  1. Git011--分支管理策略
  2. Codeforces 1025D(区间dp)
  3. L8.1 lvs+heartbeat-ldirectord实现高可用负载均衡
  4. 接口responsecode返回500_springboot+redis+Interceptor+annotation实现接口自动幂(989)
  5. python+selenium自动化测试——浏览器驱动
  6. Win10卸载python总是提示error2503失败各种解决办法
  7. cocos2dx blender 骨骼动画实现
  8. hash地址_深入浅出一致性Hash原理
  9. node.js模块引擎
  10. 安全登录代码 php,PHP登录怎么写安全
  11. socket接收的消息怎么更新到页面_利用socketio实现简易即时消息服务
  12. linux查看端口出现unix,linux查看端口被占用状况
  13. AutoJs学习-实现取色器
  14. 招商证券交易系统宕机上热搜,遭深圳证监局责令整改
  15. 周记——20150720
  16. 希尔伯特的23个问题
  17. 学得到专栏作者如何回答问题:万维钢(1)
  18. 在群晖中批量删除重复文件
  19. PS 的形状工具的布尔运算
  20. Service Mesh Summit 服务网格峰会 2022 正在报名中

热门文章

  1. 百度文库新一代文档阅读器,核心技术点全解析
  2. request 的相关请求方法
  3. 用html和css写一个动态的圣诞节贺卡
  4. argc argv
  5. python微信刷屏_拍一拍,微信史上最短一行代码
  6. druid连接池因数据库故障导致主线程挂起停止响应的优化
  7. 小米8手机上PDF文件转Word如何转换?
  8. java calendar日期计算_利用Java中Calendar计算两个日期之间的天数和周数
  9. 计算机的英语显示,电脑开机后显示英文是为什么?
  10. H5 + vue 监听手机屏幕旋转及判断横竖屏