Java計(jì)算兩個(gè)時(shí)間段的差的實(shí)例詳解
在本文中,讓我們探索各種方法來(lái)找出 Java 中兩個(gè)時(shí)間段之間的差異。為簡(jiǎn)單起見(jiàn),假設(shè)提供給我們的時(shí)間段格式為 HH:MM:SS
例子
輸入:第一個(gè)時(shí)間段:- 18:00:00 第二時(shí)間段:- 21:00:00 輸出: 3小時(shí)0分0秒 輸入:第一個(gè)時(shí)間段:- 17:00:00 第二時(shí)間段:- 23:22:00 輸出: 6小時(shí)22分0秒
方法 1 :- 使用 SimpleDateFormat 類和 Date 類
JDK 第 7 版的 java.text 包中添加了 SimpleDateFormat 類。通過(guò)創(chuàng)建 SimpleDateFormat 對(duì)象以 HH:MM:SS 格式解析時(shí)間段。SimpleDateFormat 對(duì)象解析時(shí)間段并返回一個(gè)日期對(duì)象,該對(duì)象可用于計(jì)算經(jīng)過(guò)的時(shí)間。
以下是上述方法的代碼:
// 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. "); } }
輸出
時(shí)差是 10 小時(shí) 29 分 10 秒。
時(shí)間復(fù)雜度: O(1)
方法 2 :- 使用 LocalTime 和 ChronoUnit 類
Java 在第 8 版 JDK 中帶來(lái)了大量特性,其中很少有 java.time 包中的 LocalTime 和 ChronoUnit 類。LocalTime 對(duì)象以 HH:MM:SS 格式解析日期,而 ChronoUnit 用于獲取小時(shí)、分鐘和秒的差異。
以下是上述方法的代碼:
// 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小時(shí)22分0秒。
時(shí)間復(fù)雜度: O(1)
實(shí)例擴(kuò)展
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 日期對(duì)象 */ 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)化錯(cuò)誤"); } return date; } /** * 將指定的日期格式化成指定的日期字符串 * @param date 日期對(duì)象 * @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 日期對(duì)象 * @param days 天數(shù) * @return 日期對(duì)象 */ 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對(duì)象 * @return Date對(duì)象 */ @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對(duì)象 * @param date Date對(duì)象 * @return LocalDate對(duì)象 */ @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計(jì)算兩個(gè)時(shí)間段的差的實(shí)例詳解的文章就介紹到這了,更多相關(guān)Java計(jì)算兩個(gè)時(shí)間段的差內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot、Java 使用 Jsoup 解析 HTML 頁(yè)面
這篇文章主要介紹了SpringBoot、Java 使用 Jsoup 解析 HTML 頁(yè)面的詳細(xì)步驟,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08淺談SpringBoot實(shí)現(xiàn)異步調(diào)用的幾種方式
本文主要介紹了淺談SpringBoot實(shí)現(xiàn)異步調(diào)用的幾種方式,主要包括CompletableFuture異步任務(wù),基于@Async異步任務(wù), TaskExecutor異步任務(wù),感興趣的可以了解一下2023-11-11解決SpringBoot下Redis序列化亂碼的問(wèn)題
這篇文章主要介紹了解決SpringBoot下Redis序列化亂碼的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06tk.mybatis如何擴(kuò)展自己的通用mapper
這篇文章主要介紹了tk.mybatis如何擴(kuò)展自己的通用mapper操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06詳解如何給Sprintboot應(yīng)用添加插件機(jī)制
這篇文章主要為大家介紹了如何給 Sprintboot 應(yīng)用添加插件機(jī)制,文中有詳細(xì)的解決方案及示例代碼,具有一定的參考價(jià)值,需要的朋友可以參考下2023-08-08JAVA基于Redis實(shí)現(xiàn)計(jì)數(shù)器限流的使用示例
計(jì)數(shù)器法是限流算法里最簡(jiǎn)單也是最容易實(shí)現(xiàn)的一種算法,本文主要介紹了JAVA基于Redis實(shí)現(xiàn)計(jì)數(shù)器限流的使用示例,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09java中實(shí)現(xiàn)list或set轉(zhuǎn)map的方法
這篇文章主要介紹了java中實(shí)現(xiàn)list或set轉(zhuǎn)map的方法的相關(guān)資料,需要的朋友可以參考下2017-01-01詳解Spring 基于 Aspect 注解的增強(qiáng)實(shí)現(xiàn)
本篇文章主要介紹了詳解Spring 基于 Aspect 注解的增強(qiáng)實(shí)現(xiàn),非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-04-04