为什么如果我使用String.format(Date)
,它会以默认时区打印日期,但当我使用String.format(Calendar)
时,它会以日历的时区打印。实际上,后者正是我所需要的,但我能确定这种行为会持续下去吗?
最佳答案
正如我从 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
的参数是日期,则使用Calendar.getInstance(Locale)
,如果参数是,则使用默认时区创建日历日历
然后使用日历的时区。此外,我没有找到对此的任何明确描述,并且该方法是私有(private)的,因此不可能假设此行为不会改变。
关于java - 使用 String.format() 处理日历与日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12913959/