更新時間:2022-10-31 10:01:08 來源:動力節點 瀏覽2463次
在本文中,讓我們探索各種方法來找出 Java 中兩個時間段之間的差異。為簡單起見,假設提供給我們的時間段格式為 HH:MM:SS
例子
輸入:第一個時間段:- 18:00:00
第二時間段:- 21:00:00
輸出: 3小時0分0秒
輸入:第一個時間段:- 17:00:00
第二時間段:- 23:22:00
輸出: 6小時22分0秒
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)
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)
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習