Java计算两个时间段的差的实例详解

 更新时间:2022年11月06日 15:12:43   作者:bjpowernode  
在本篇内容中,我们给大家整理了关于Java计算两个时间段的差的实例内容,并做了详细分析,有需要的朋友们学习下。

在本文中,让我们探索各种方法来找出 Java 中两个时间段之间的差异。为简单起见,假设提供给我们的时间段格式为 HH:MM:SS

例子

输入:第一个时间段:- 18:00:00
    第二时间段:- 21:00:00
输出: 3小时0分0秒
输入:第一个时间段:- 17:00:00
        第二时间段:- 23:22:00
输出: 6小时22分0秒

方法 1 :- 使用 SimpleDateFormat 类和 Date 类

JDK 第 7 版的 java.text 包中添加了 SimpleDateFormat 类。通过创建 SimpleDateFormat 对象以 HH:MM:SS 格式解析时间段。SimpleDateFormat 对象解析时间段并返回一个日期对象,该对象可用于计算经过的时间。

以下是上述方法的代码:

// Java Program to Find the difference
// between Two Time Periods
// Importing the Date Class from the util package
import java.util.*;
// Importing the SimpleDateFormat
// Class from the text package
import java.text.*;
public class GFG {
	public static void main(String[] args) throws Exception
	{
		// Dates to be parsed
		String time1 = "18:00:00";
		String time2 = "7:30:50";
		// Creating a SimpleDateFormat object
		// to parse time in the format HH:MM:SS
		SimpleDateFormat simpleDateFormat
			= new SimpleDateFormat("HH:mm:ss");
		// Parsing the Time Period
		Date date1 = simpleDateFormat.parse(time1);
		Date date2 = simpleDateFormat.parse(time2);
		// Calculating the difference in milliseconds
		long differenceInMilliSeconds
			= Math.abs(date2.getTime() - date1.getTime());
		// Calculating the difference in Hours
		long differenceInHours
			= (differenceInMilliSeconds / (60 * 60 * 1000))
			% 24;
		// Calculating the difference in Minutes
		long differenceInMinutes
			= (differenceInMilliSeconds / (60 * 1000)) % 60;
		// Calculating the difference in Seconds
		long differenceInSeconds
			= (differenceInMilliSeconds / 1000) % 60;
		// Printing the answer
		System.out.println(
			"Difference is " + differenceInHours + " hours "
			+ differenceInMinutes + " minutes "
			+ differenceInSeconds + " Seconds. ");
	}
}

输出

时差是 10 小时 29 分 10 秒。

时间复杂度: O(1)

方法 2 :- 使用 LocalTime 和 ChronoUnit 类

Java 在第 8 版 JDK 中带来了大量特性,其中很少有 java.time 包中的 LocalTime 和 ChronoUnit 类。LocalTime 对象以 HH:MM:SS 格式解析日期,而 ChronoUnit 用于获取小时、分钟和秒的差异。

以下是上述方法的代码:

// Java program to get the difference
// between Two Time Periods in Java
// Importing the LocalTime class
import java.time.*;
// Importing the ChronoUnit class
import java.time.temporal.ChronoUnit;
class GFG {
	public static void main(String[] args)
	{
		// Parsing Time Period in the format HH:MM:SS
		LocalTime time1 = LocalTime.of(18, 00, 00);
		LocalTime time2 = LocalTime.of(21, 22, 00);
		// Calculating the difference in Hours
		long hours = ChronoUnit.HOURS.between(time1, time2);
		// Calculating the difference in Minutes
		long minutes
			= ChronoUnit.MINUTES.between(time1, time2) % 60;
		// Calculating the difference in Seconds
		long seconds
			= ChronoUnit.SECONDS.between(time1, time2) % 60;
		// Printing the difference
		System.out.println(
			"Difference is " + hours + " hours " + minutes
			+ " minutes " + seconds + " seconds.");
	}
}

输出

相差3小时22分0秒。

时间复杂度: O(1)

实例扩展

import android.os.Build;
import androidx.annotation.RequiresApi;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * Description: 日期工具类
 */
public class MyDateUtil {
 /**
 * 将指定的日期字符串转换成日期
 * @param dateStr 日期字符串
 * @param pattern 格式
 * @return 日期对象
 */
 public static Date parseDate(String dateStr, String pattern)
 {
 SimpleDateFormat sdf = new SimpleDateFormat(pattern);
 Date date;
 try {
  date = sdf.parse(dateStr);
 } catch (ParseException e) {
  throw new RuntimeException("日期转化错误");
 }
 return date;
 }
 /**
 * 将指定的日期格式化成指定的日期字符串
 * @param date 日期对象
 * @param pattern 格式
 * @return 格式化后的日期字符串
 */
 public static String dateFormate(Date date, String pattern)
 {
 SimpleDateFormat sdf = new SimpleDateFormat(pattern);
 String dateStr;
 if(date == null)
 {
  return "";
 }
 dateStr = sdf.format(date);
 return dateStr;
 }
 /**
 * 查询指定日期前后指定的天数
 * @param date 日期对象
 * @param days 天数
 * @return 日期对象
 */
 public static Date incr(Date date, int days)
 {
 if (date == null){
  return null;
 }
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(date);
 calendar.add(Calendar.DAY_OF_MONTH, days);
 return calendar.getTime();
 }

 /**
 * 将LocalDate日期转化成Date
 * @param localDate LocalDate对象
 * @return Date对象
 */
 @RequiresApi(api = Build.VERSION_CODES.O)
 public static Date localDateToDate(LocalDate localDate)
 {
 if (localDate == null)
 {
  return null;
 }
 ZoneId zoneId = ZoneId.systemDefault();
 ZonedDateTime zonedDateTime = localDate.atStartOfDay(zoneId);
 Date date = Date.from(zonedDateTime.toInstant());
 return date;
 }
 /**
 * 将Date转成LocalDate对象
 * @param date Date对象
 * @return LocalDate对象
 */
 @RequiresApi(api = Build.VERSION_CODES.O)
 public static LocalDate dateToLocalDate(Date date)
 {
 if (date == null)
 {
  return null;
 }
 ZoneId zoneId = ZoneId.systemDefault();
 Instant instant = date.toInstant();
 LocalDate localDate = instant.atZone(zoneId).toLocalDate();
 return localDate;
 }
}

到此这篇关于Java计算两个时间段的差的实例详解的文章就介绍到这了,更多相关Java计算两个时间段的差内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java使用itextpdf实现生成PDF并添加图片,水印和文字

    Java使用itextpdf实现生成PDF并添加图片,水印和文字

    这篇文章主要为大家详细介绍了Java在使用itextpdf实现生成PDF时如何实现添加图片,水印和文字等效果,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-02-02
  • JAVA SFTP文件上传、下载及批量下载实例

    JAVA SFTP文件上传、下载及批量下载实例

    本篇文章主要介绍了JAVA SFTP文件上传、下载及批量下载实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2017-03-03
  • Java中操作数组的Arrays类

    Java中操作数组的Arrays类

    大家好,本篇文章主要讲的是Java中操作数组的Arrays类,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-02-02
  • Kafka源码系列教程之删除topic

    Kafka源码系列教程之删除topic

    这篇文章主要给大家介绍了关于Kafka源码系列教程之删除topic的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-08-08
  • Spring的IOC代码解析

    Spring的IOC代码解析

    这篇文章主要介绍了Spring的IOC代码解析,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Java编写Mapreduce程序过程浅析

    Java编写Mapreduce程序过程浅析

    MapReduce是一种用于处理大规模数据集的并行编程模型,其特点高效性和可扩展性,在本文中,我们将深入了解MapReduce,并使用Java编写一个简单的MapReduce程序,需要的朋友可以参考下
    2023-05-05
  • Java实现基于token认证的方法示例

    Java实现基于token认证的方法示例

    这篇文章主要介绍了Java实现基于token认证的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • Java中实现树形菜单的两种方式

    Java中实现树形菜单的两种方式

    这篇文中,我一共会用两种方式来实现目录树的数据结构,两种写法逻辑是一样的,只是一种适合新手理解,一种看着简单明了但是对于小白不是很好理解,在这里我会很详细的讲解每一步代码,主要是方便新人看懂,弥补曾经自己学习过程中的苦恼,需要的朋友可以参考下
    2023-09-09
  • 浅谈Java源码ConcurrentHashMap

    浅谈Java源码ConcurrentHashMap

    最近刚入门java,觉得看源码挺有意思的,就记录一下一些常用类的源码吧,从而能够总结一些使用细节.本文对源码ConcurrentHashMap介绍的非常详细,对正在学习java的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-05-05
  • springboot使用校验框架validation校验的示例

    springboot使用校验框架validation校验的示例

    这篇文章主要介绍了springboot使用校验框架validation校验的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02

最新评论