Java獲取時間差(天數(shù)差,小時差,分鐘差)代碼示例
網(wǎng)上有很多博文是講如何獲取時間差的,我看了一下,多數(shù)是使用Calendar類來實現(xiàn),但是都講得比較亂,在這里我用SimpleDateFormat來實現(xiàn),比較簡單,我認(rèn)為比較適合拿來用。
SimpleDateFormat 是一個以國別敏感的方式格式化和分析數(shù)據(jù)的具體類。 它允許格式化 (date -> text)、語法分析 (text -> date)和標(biāo)準(zhǔn)化。
SimpleDateFormat 允許以為日期-時間格式化選擇任何用戶指定的方式啟動。 但是,希望用 DateFormat 中的 getTimeInstance、 getDateInstance 或 getDateTimeInstance 創(chuàng)建一個日期-時間格式化程序。 每個類方法返回一個以缺省格式化方式初始化的日期/時間格式化程序。 可以根據(jù)需要用 applyPattern 方法修改格式化方式。
首先我們先初始化我們的SimpleDateFormat
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");//如2016-08-10 20:40
1.計算天數(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.計算小時差
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.計算分鐘差:
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ù)差,小時差,分鐘差)代碼示例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:
Java編程實現(xiàn)時間和時間戳相互轉(zhuǎn)換實例
如有不足之處,歡迎留言指出。
相關(guān)文章
Springboot通過Scheduled實現(xiàn)定時任務(wù)代碼
這篇文章主要介紹了Springboot通過Scheduled實現(xiàn)定時任務(wù)代碼,具有一定參考價值,需要的朋友可以了解下。2017-11-11
java使用freemarker模板生成html再轉(zhuǎn)為pdf
這篇文章主要為大家詳細介紹了java如何使用freemarker模板生成html,再利用iText將生成的HTML轉(zhuǎn)換為PDF文件,感興趣的小伙伴可以參考下2025-04-04
基于idea操作hbase數(shù)據(jù)庫并映射到hive表
這篇文章主要介紹了用idea操作hbase數(shù)據(jù)庫,并映射到hive,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03
詳解json string轉(zhuǎn)換為java bean及實例代碼
這篇文章主要介紹了詳解json string轉(zhuǎn)換為java bean及實例代碼的相關(guān)資料,這里提供實例代碼幫助大家理解,需要的朋友可以參考下2017-07-07
springboot log4j2不能打印框架錯誤日志的解決方案
這篇文章主要介紹了springboot log4j2不能打印框架錯誤日志的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

