<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
很多朋友都想知道java怎麼獲取時間差?下面就一起來了解一下吧~
Java獲取時間差(天數差,小時差,分鐘差)代碼示例。
SimpleDateFormat 允許以爲日期-時間格式化選擇任何用戶指定的方式啓動。每個類方法返回一個以缺省格式化方式初始化的日期/時間格式化程序。 可以根據需要用 applyPattern 方法修改格式化方式。
首先要初始化SimpleDateFormat1
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");//如2016-08-10 20:40
1.計算天數差。
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))
以上就是關於Java獲取時間差(天數差,小時差,分鐘差)代碼示例的全部內容,希望能夠幫到大家。