SimpleDateFormat的使用 时间差的计算 SimpleDateFormat 转换格式异常(线程安全问题)

基本格式:

SimpleDateFormat simpleFormat = new SimpleDateFormat(

"yyyy-MM-dd HH:mm:ss");


线程安全问题分析

SimpleDateFormat 的变量若是一个静态变量,并在不同的线程中使用,就有可能造成转换格式异常的问题(例如转换年月日时分就有可能出现2018-07-05 0009:50 情况,转换年月日就可能出现2018-06-0015现象),这种情况是由于多个线程同时使用SimpleDateFormat对象造成的,而这种情况是由于SimpleFormat内部是由一个Calendar控制的,当SimpleDateFormat静态时,Calendar也就被共享了,多个线程同时操作Calendar就会出现问题。

解决办法

一、每个线程拥有自己的SimpleDateFormat对象,即每个线程使用sdf对象时就new 一个新的。(浪费资源)

二、对使用Sdf的线程加锁,使sdf的使用只能同步进行(耗时)

三、使用线程安全的时间转换 FastDateFormat  org.apache.commons.lang3.time包

四、使用ThreadLocal:





参考:

https://blog.csdn.net/zdp072/article/details/41044059

https://www.cnblogs.com/zemliu/archive/2013/08/29/3290585.html

https://www.cnblogs.com/lion88/p/6426019.html

FaseDateFormat的参考:

https://blog.csdn.net/insistgogo/article/details/22393441

ThreadLocal的参考:

https://mp.csdn.net/postedit

https://www.jb51.net/article/109562.htm

https://segmentfault.com/a/1190000011264294



时间差的计算

SimpleDateFormat simpleFormat = new SimpleDateFormat(

"yyyy-MM-dd HH:mm:ss");
try {
Date xdsj = (Date) simpleFormat.parse("2017-09-18 10:10:30");
Date jzsj = (Date) simpleFormat.parse("2017-09-20 16:30:10");
long xdsjKs = xdsj.getTime();
long jzsjJs = jzsj.getTime();
long sjc = jzsjJs - xdsjKs;
int day = (int) (sjc / (1000 * 60 * 60 * 24));// 剩余的天数
int hour = (int) ((sjc % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));// 剩余的小时数
int minute = (int) (((sjc % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60)) / (1000 * 60));// 剩余的分钟数
int second = (int) ((((sjc % (1000 * 60 * 60 * 24)) % (1000 * 60 * 60)) % (1000 * 60)) / 1000);
System.out.println("天:" + day + "小时:" + hour + "分钟:" + minute
+ "秒:" + second);
} catch (ParseException e) {
e.printStackTrace();
}


SimpleDateFormat simpleFormat = new SimpleDateFormat(

"yyyy-MM-dd HH:mm:ss");
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值