网上有很多博文是讲如何获取时间差的,我看了一下,多数是使用Calendar类来实现,但是都讲得比较乱,在这里我用SimpleDateFormat来实现,比较简单,我认为比较适合拿来用。
SimpleDateFormat 是一个以国别敏感的方式格式化和分析数据的具体类。 它允许格式化 (date -> text)、语法分析 (text -> date)和标准化。
SimpleDateFormat 允许以为日期-时间格式化选择任何用户指定的方式启动。 但是,希望用 DateFormat 中的 getTimeInstance、 getDateInstance 或 getDateTimeInstance 创建一个日期-时间格式化程序。 每个类方法返回一个以缺省格式化方式初始化的日期/时间格式化程序。 可以根据需要用 applyPattern 方法修改格式化方式。
首先我们先初始化我们的SimpleDateFormat
?
1
|
SimpleDateFormat simpleFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm" ); //如2016-08-10 20:40
|
1.计算天数差。
?
1
2
3
4
5
|
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.计算小时差
?
1
2
3
4
5
|
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.计算分钟差:
?
1
2
3
4
5
|
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获取时间差(天数差,小时差,分钟差)代码示例的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。
原文链接:http://blog.csdn.net/jeffleo/article/details/52175998
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-06-04 104
-
2025-06-04 99
-
2025-05-25 89
-
2025-05-27 34
-
2025-05-29 70
热门评论