java - 使用 String.format() 处理日历与日期

标签 java date

为什么如果我使用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/

相关文章:

java - Hibernate HQL 和日期

Java NoClassDefFoundError 即使 Jars 在同一文件夹中

java - 在 2D 数组 (8x8) 中,如何递归打印从起始位置到结束位置的连续数字?

java - ActionListeners 出现 Stackoverflow 错误

javascript - 在 MongoDB 中存储日期而不考虑时区

Java - 日期保存为前一天

php - 在 PHP 中获取实时时间和日期

JavaFX : avoid thread-code in Model Setters

java - 是否有与 QSqlTableModel 等效的 Java ORM?

date - 在 Neo4J 中使用 Cypher 将 DateTime 转换为 Epoch 毫秒