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)文章
JAVA 生成隨機(jī)數(shù)并根據(jù)后臺(tái)概率靈活生成的實(shí)例代碼
本篇文章主要介紹了JAVA 生成隨機(jī)數(shù)并根據(jù)后臺(tái)概率靈活生成的實(shí)例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08
Java實(shí)現(xiàn)京東聯(lián)盟API數(shù)據(jù)獲取功能
這篇文章介紹了Java獲取京東聯(lián)盟API數(shù)據(jù)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
SpringBoot+WebSocket實(shí)現(xiàn)IM及時(shí)通訊的代碼示例
項(xiàng)目中碰到需要及時(shí)通訊的場(chǎng)景,使用springboot集成websocket,即可實(shí)現(xiàn)簡(jiǎn)單的及時(shí)通訊,本文介紹springboot如何集成websocket、IM及時(shí)通訊需要哪些模塊、開(kāi)發(fā)和部署過(guò)程中遇到的問(wèn)題、以及實(shí)現(xiàn)小型IM及時(shí)通訊的代碼,需要的朋友可以參考下2023-10-10
Spring框架實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼功能的代碼示例
之前項(xiàng)目需要在驗(yàn)證碼模塊,增加滑動(dòng)驗(yàn)證碼,用來(lái)給手機(jī)端使用的,大概看了下,主要方法就是將圖片切割,然后記住偏移量,進(jìn)行滑動(dòng),所以本文給大家介紹了Spring框架實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼功能的方法示例,需要的朋友可以參考下2024-07-07
使用Spring源碼報(bào)錯(cuò)java:找不到類 InstrumentationSavingAgent的問(wèn)題
這篇文章主要介紹了使用Spring源碼報(bào)錯(cuò)java:找不到類 InstrumentationSavingAgent的問(wèn)題,本文給大家分享解決方法,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
Java設(shè)計(jì)模式中的工廠及抽象工廠模式解析
這篇文章主要介紹了Java設(shè)計(jì)模式中的工廠及抽象工廠模式解析,工廠模式作為創(chuàng)建型設(shè)計(jì)模式中常見(jiàn)的設(shè)計(jì)方法,一般情況下,工廠模式分為3種,簡(jiǎn)單工作、工廠方法、抽象工作,其實(shí)簡(jiǎn)單工廠只是工廠方法的一種特例,需要的朋友可以參考下2023-12-12

