Java獲取時(shí)間差(天數(shù)差,小時(shí)差,分鐘差)代碼示例
網(wǎng)上有很多博文是講如何獲取時(shí)間差的,我看了一下,多數(shù)是使用Calendar類來(lái)實(shí)現(xiàn),但是都講得比較亂,在這里我用SimpleDateFormat來(lái)實(shí)現(xiàn),比較簡(jiǎn)單,我認(rèn)為比較適合拿來(lái)用。
SimpleDateFormat 是一個(gè)以國(guó)別敏感的方式格式化和分析數(shù)據(jù)的具體類。 它允許格式化 (date -> text)、語(yǔ)法分析 (text -> date)和標(biāo)準(zhǔn)化。
SimpleDateFormat 允許以為日期-時(shí)間格式化選擇任何用戶指定的方式啟動(dòng)。 但是,希望用 DateFormat 中的 getTimeInstance、 getDateInstance 或 getDateTimeInstance 創(chuàng)建一個(gè)日期-時(shí)間格式化程序。 每個(gè)類方法返回一個(gè)以缺省格式化方式初始化的日期/時(shí)間格式化程序。 可以根據(jù)需要用 applyPattern 方法修改格式化方式。
首先我們先初始化我們的SimpleDateFormat
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");//如2016-08-10 20:40
1.計(jì)算天數(shù)差。
String fromDate = simpleFormat.format("2016-05-01 12:00"); String toDate = simpleFormat.format("2016-06-01 12:00"); long from = simpleFormat.parse(fromDate).getTime(); long to = simpleFormat.parse(toDate).getTime(); int days = (int) ((to - from)/(1000 * 60 * 60 * 24));
2.計(jì)算小時(shí)差
String fromDate = simpleFormat.format("2016-05-01 12:00"); String toDate = simpleFormat.format("2016-05-01 14:00"); long from = simpleFormat.parse(fromDate).getTime(); long to = simpleFormat.parse(toDate).getTime(); int hours = (int) ((to - from)/(1000 * 60 * 60));
3.計(jì)算分鐘差:
String fromDate = simpleFormat.format("2016-05-01 12:00"); String toDate = simpleFormat.format("2016-05-01 12:50"); long from = simpleFormat.parse(fromDate).getTime(); long to = simpleFormat.parse(toDate).getTime(); int minutes = (int) ((to - from)/(1000 * 60));
總結(jié)
以上就是本文關(guān)于Java獲取時(shí)間差(天數(shù)差,小時(shí)差,分鐘差)代碼示例的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:
Java編程實(shí)現(xiàn)時(shí)間和時(shí)間戳相互轉(zhuǎn)換實(shí)例
如有不足之處,歡迎留言指出。
相關(guān)文章
基于Spring?Boot的線程池監(jiān)控問(wèn)題及解決方案
這篇文章主要介紹了基于Spring?Boot的線程池監(jiān)控方案,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03Java并發(fā)編程this逃逸問(wèn)題總結(jié)
本篇文章給大家詳細(xì)分析了Java并發(fā)編程this逃逸的問(wèn)題分享,對(duì)此有需要的朋友參考下。2018-02-02Spring Boot Admin實(shí)現(xiàn)服務(wù)健康預(yù)警功能
這篇文章主要介紹了Spring Boot Admin實(shí)現(xiàn)服務(wù)健康預(yù)警功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05Java 詳細(xì)講解分治算法如何實(shí)現(xiàn)歸并排序
分治算法的基本思想是將一個(gè)規(guī)模為N的問(wèn)題分解為K個(gè)規(guī)模較小的子問(wèn)題,這些子問(wèn)題相互獨(dú)立且與原問(wèn)題性質(zhì)相同。求出子問(wèn)題的解,就可得到原問(wèn)題的解,本篇文章我們就用分治算法來(lái)實(shí)現(xiàn)歸并排序2022-04-04CountDownLatch和Atomic原子操作類源碼解析
這篇文章主要為大家介紹了CountDownLatch和Atomic原子操作類的源碼解析以及理解應(yīng)用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03