-1

There set 2019-12-27, but print result is 2020-01-27. Is there mistake in the code?

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));
}
a_chubenko
  • 147
  • 2
  • 13
  • 6
    In the legacy `java.util.Calendar` class, months are 0-indexed,so December is 11. But don't use that, use the `java.time` package instead. – Joe C Dec 30 '18 at 20:45
  • 1
    You are using terrible old classes that were supplanted years ago by the *java.time* classes. Unlike the legacy classes, the modern classes use **sane numbering, such as 1-12 for January-December**, and 1-7 for Monday-Sunday. `LocalDate.of( 2019 , 12 , 27 ).toString()` ➙ `2019-12-27`. For more clarity, use the `Month` enum. `LocalDate.of( 2019 , Month.DECEMBER , 27 ).toString()` – Basil Bourque Dec 30 '18 at 23:16
  • **Search Stack Overflow** before posting. You can assume any basic date-time question has already been asked and answered. – Basil Bourque Dec 30 '18 at 23:21

1 Answers1

1

months are 0-based: from documentation:

/**
 * 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);
}
Bartosz Wardziński
  • 6,185
  • 1
  • 19
  • 30
  • 1
    Better to steer people towards the *java.time* classes that supplanted these terrible old date-time classes with the adoption of [JSR 310](https://jcp.org/en/jsr/detail?id=310). Encouraging the use of `Calendar` in 2018 is poor advice. – Basil Bourque Dec 30 '18 at 23:20