广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java计算两个时间段的差的实例详解
  • 641
分享到

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

Java计算时间段差 2022-11-13 19:11:46 641人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

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

在本文中,让我们探索各种方法来找出 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;


public class MyDateUtil {
 
 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;
 }
 
 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;
 }
 
 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();
 }

 
 @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;
 }
 
 @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计算两个时间段的差内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Java计算两个时间段的差的实例详解

本文链接: https://www.lsjlt.com/news/170848.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作