HttpClient DateUtils 的時區問題


問題:

  今天在做測試發現傳入的時間為 "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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM