問題:
今天在做測試發現傳入的時間為 "2018-11-26" 在格式化后變成了"20181125"
DateUtils.formatDate(c.getTime(), "yyyyMMdd")
解析工具使用的是httpClient 4.5
想法:
1、不應該啊,這應該是比較常見的API
2、這種常見的時間解析問題出錯,那么應該是時區設置錯誤
3、debug到 工具類內部,發現
1 SimpleDateFormat format = formats.get(pattern); 2 if (format == null) { 3 format = new SimpleDateFormat(pattern, Locale.US); 4 format.setTimeZone(TimeZone.getTimeZone("GMT")); 5 formats.put(pattern, format); 6 }
這使用了GMT 時區,和我們本地的時區差了8個小時;
這個感覺設置得不是很友好,查看了下SimpleDateFormat 的初始化,感覺要人性化一點;
1 private void initializeCalendar(Locale loc) { 2 if (calendar == null) { 3 assert loc != null; 4 // The format object must be constructed using the symbols for this zone. 5 // However, the calendar should use the current default TimeZone. 6 // If this is not contained in the locale zone strings, then the zone 7 // will be formatted using generic GMT+/-H:MM nomenclature. 8 calendar = Calendar.getInstance(TimeZone.getDefault(), loc); 9 } 10 }