java获取时间差

<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));

java获取时间差

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获取时间差(天数差,小时差,分钟差)代码示例的全部内容,希望能够帮到大家。