基本格式:
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");