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     }

猜你喜欢

转载自www.cnblogs.com/souyoulang/p/10023757.html