Stacked Q&A

Java - Calendar.getTime does not retrieve the date set with Calendar.setTime
  • 1 voting
  • 2022-05-25 00:00

    I have the following code in Java

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    
    public class Test {
        public static void main(String[] args) {
            try {
                SimpleDateFormat SDF = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss");
                Calendar date = Calendar.getInstance();
                date.setTime(SDF.parse("2011-02-01T00:00:00"));
                System.out.println(SDF.format(date.getTime()));
            } catch (Exception e) {
    
            }
        }
    }
    

    I expect to see in the console the following string

    2011-02-01T00:00:00
    

    instead I see

    2011-12-26T00:00:00
    

    What can be wrong?

  • 5 553 0 0
첨부 파일
답변
총 5개의 답변이있습니다.
  • 답변일: 2022-05-25 00:00

    I change the format: "yyyy-MM-dd'T'HH:mm:ss"

    SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Calendar date = Calendar.getInstance();
    date.setTime(SDF.parse("2011-02-01T00:00:00"));
    System.out.println(SDF.format(date.getTime()));
    

    The output is 2011-02-01T00:00:00

    "Y": week year

    "y": year

    https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

    From the documentation:

    "If week year 'Y' is specified and the calendar doesn't support any week years, the calendar year ('y') is used instead. The support of week years can be tested with a call to getCalendar().isWeekDateSupported()."

    In some calendar "Y" and "y" are the same, but is not the case of the gregorian calendar.

    https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#isWeekDateSupported%28%29

  • 0 0 채택된 답변 퍼블 채택!
Tages
    활동순위
    유저
      파트너사