Java計算兩個時間段的差的實例詳解
在本文中,讓我們探索各種方法來找出 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 類。通過創(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 { /** * 將指定的日期字符串轉換成日期 * @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; } /** * 查詢指定日期前后指定的天數(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日期轉化成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; } }
到此這篇關于Java計算兩個時間段的差的實例詳解的文章就介紹到這了,更多相關Java計算兩個時間段的差內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot、Java 使用 Jsoup 解析 HTML 頁面
這篇文章主要介紹了SpringBoot、Java 使用 Jsoup 解析 HTML 頁面的詳細步驟,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08淺談SpringBoot實現(xiàn)異步調(diào)用的幾種方式
本文主要介紹了淺談SpringBoot實現(xiàn)異步調(diào)用的幾種方式,主要包括CompletableFuture異步任務,基于@Async異步任務, TaskExecutor異步任務,感興趣的可以了解一下2023-11-11JAVA基于Redis實現(xiàn)計數(shù)器限流的使用示例
計數(shù)器法是限流算法里最簡單也是最容易實現(xiàn)的一種算法,本文主要介紹了JAVA基于Redis實現(xiàn)計數(shù)器限流的使用示例,具有一定的參考價值,感興趣的可以了解一下2023-09-09詳解Spring 基于 Aspect 注解的增強實現(xiàn)
本篇文章主要介紹了詳解Spring 基于 Aspect 注解的增強實現(xiàn),非常具有實用價值,需要的朋友可以參考下2017-04-04