Java計算兩個時間段的差的實例詳解
在本文中,讓我們探索各種方法來找出 Java 中兩個時間段之間的差異。為簡單起見,假設(shè)提供給我們的時間段格式為 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 類。通過創(chuàng)建 SimpleDateFormat 對象以 HH:MM:SS 格式解析時間段。SimpleDateFormat 對象解析時間段并返回一個日期對象,該對象可用于計算經(jīng)過的時間。
以下是上述方法的代碼:
// 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 {
/**
* 將指定的日期字符串轉(zhuǎn)換成日期
* @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("日期轉(zhuǎn)化錯誤");
}
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;
}
/**
* 查詢指定日期前后指定的天數(shù)
* @param date 日期對象
* @param days 天數(shù)
* @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日期轉(zhuǎn)化成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轉(zhuǎn)成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;
}
}到此這篇關(guān)于Java計算兩個時間段的差的實例詳解的文章就介紹到這了,更多相關(guān)Java計算兩個時間段的差內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JAVA 生成隨機數(shù)并根據(jù)后臺概率靈活生成的實例代碼
本篇文章主要介紹了JAVA 生成隨機數(shù)并根據(jù)后臺概率靈活生成的實例代碼,具有一定的參考價值,有興趣的可以了解一下2017-08-08
Java實現(xiàn)京東聯(lián)盟API數(shù)據(jù)獲取功能
這篇文章介紹了Java獲取京東聯(lián)盟API數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07
SpringBoot+WebSocket實現(xiàn)IM及時通訊的代碼示例
項目中碰到需要及時通訊的場景,使用springboot集成websocket,即可實現(xiàn)簡單的及時通訊,本文介紹springboot如何集成websocket、IM及時通訊需要哪些模塊、開發(fā)和部署過程中遇到的問題、以及實現(xiàn)小型IM及時通訊的代碼,需要的朋友可以參考下2023-10-10
使用Spring源碼報錯java:找不到類 InstrumentationSavingAgent的問題
這篇文章主要介紹了使用Spring源碼報錯java:找不到類 InstrumentationSavingAgent的問題,本文給大家分享解決方法,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10

