很多朋友都想知道java怎么獲取時(shí)間差?下面就一起來了解一下吧~
Java獲取時(shí)間差(天數(shù)差,小時(shí)差,分鐘差)代碼示例。
SimpleDateFormat 允許以為日期-時(shí)間格式化選擇任何用戶指定的方式啟動(dòng)。每個(gè)類方法返回一個(gè)以缺省格式化方式初始化的日期/時(shí)間格式化程序。 可以根據(jù)需要用 applyPattern 方法修改格式化方式。
首先要初始化SimpleDateFormat1
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))
以上就是關(guān)于Java獲取時(shí)間差(天數(shù)差,小時(shí)差,分鐘差)代碼示例的全部內(nèi)容,希望能夠幫到大家。