垃圾站 生活小记 Java计算两个时间段的差的实例详解

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

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

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

例子

输入:第一个时间段:- 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;
 }
}
上一篇
下一篇
联系我们

联系我们

返回顶部