为什么我使用String.format(Date)
它会在默认时区中打印日期,但是当我使用String.format(Calendar)
时,它会在Calendar的时区中打印。实际上,后者是我需要的,但我能确定这种行为会持续吗?
答案 0 :(得分:1)
正如我从String.format的实现中发现的那样(至少对于JDK 1.5,它有printDateTime(Object, Locale)
包含这样的代码:
} else if (arg instanceof Date) {
// Note that the following method uses an instance of the
// default time zone (TimeZone.getDefaultRef().
cal = Calendar.getInstance(l);
cal.setTime((Date)arg);
} else if (arg instanceof Calendar) {
cal = (Calendar) ((Calendar)arg).clone();
cal.setLenient(true);
} else {
因此,如果String.format
的参数是Date,则使用Calendar.getInstance(Locale)
,这会在默认时区中创建日历,如果参数为Calendar
,则使用日历的时区。此外,我没有找到任何明确的描述,并且该方法是私有的,所以不可能认为这种行为不会改变。