【问题标题】:Java Calendar monthes indexing [duplicate]Java日历月索引[重复]
【发布时间】:2019-05-27 14:53:54
【问题描述】:

设置为 2019-12-27,但打印结果为 2020-01-27。代码有错误吗?

public void testJavaDate(){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date checkInDate;
    checkInDate = new Calendar.Builder()
            .setDate(2019, 12, 27)
            .build().getTime();
    System.out.println("checkIn sdf: "+sdf.format(checkInDate));
}

【问题讨论】:

  • 在旧的 java.util.Calendar 类中,月份是 0 索引的,所以 12 月是 11。但不要使用它,而是使用 java.time 包。
  • 您正在使用多年前被 java.time 类取代的糟糕的旧类。与传统类不同,现代类使用合理的编号,例如 1-12 表示 1 月至 12 月,1-7 表示周一至周日。 LocalDate.of( 2019 , 12 , 27 ).toString()2019-12-27。为了更清楚,请使用Month 枚举。 LocalDate.of( 2019 , Month.DECEMBER , 27 ).toString()
  • 搜索 Stack Overflow,然后再发帖。您可以假设已经提出并回答了任何基本的日期时间问题。

标签: java date calendar settings


【解决方案1】:

月份是从 0 开始的: 来自文档:

/**
 * Sets the date field parameters to the values given by {@code year},
 * {@code month}, and {@code dayOfMonth}. This method is equivalent to
 * a call to:
 * <pre>
 *   setFields(Calendar.YEAR, year,
 *             Calendar.MONTH, month,
 *             Calendar.DAY_OF_MONTH, dayOfMonth);</pre>
 *
 * @param year       the {@link Calendar#YEAR YEAR} value
 * @param month      the {@link Calendar#MONTH MONTH} value
 *                   (the month numbering is <em>0-based</em>).
 * @param dayOfMonth the {@link Calendar#DAY_OF_MONTH DAY_OF_MONTH} value
 * @return this {@code Calendar.Builder}
 */
public Builder setDate(int year, int month, int dayOfMonth) {
    return setFields(YEAR, year, MONTH, month, DAY_OF_MONTH, dayOfMonth);
}

【讨论】:

  • 更好地引导人们使用 JSR 310 取代这些可怕的旧日期时间类的 java.time 类。鼓励在 2018 年使用 Calendar 是一个糟糕的建议。
猜你喜欢
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多