涉及到日期格式化工具类时,本人一直是自己造轮子,近日项目组一个兄弟用到了apache@DateUtils,在测试的时候却发现了这个类的一个bug。
先看下本人的轮子:
public static String date2String(Date date, String style)
{
SimpleDateFormat sdf = new SimpleDateFormat(style);
//TimeZone gmt = TimeZone.getTimeZone("GMT+08:00");
//sdf.setTimeZone(gmt);
if (date != null)
{
return sdf.format(date);
}
return null;
}
正常情况下,上述代码中注释掉的两行代码是可以不用加的,因为SimpleDateFormat默认会去找本机服务器的时区,然后set之,当然前提是服务器的时区设置是正确的。
而apache的DateUtils#format()方法代码如下:
public static String format(Date date, String pattern)
{
DateFormat df = createDateFormat(pattern);
return df.format(date);
}
private static DateFormat createDateFormat(String pattern)
{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
TimeZone gmt = TimeZone.getTimeZone("GMT");
sdf.setTimeZone(gmt);
sdf.setLenient(true);
return sdf;
}
注意观察,其中设置的时区是GMT,所以导致格式化出来的时间是存在偏差。
综上:在使用apache@DateUtils时,请注意此bug。