天天看點

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