1

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?

sthor69
  • 638
  • 1
  • 10
  • 25

1 Answers1

0

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

Troncador
  • 3,356
  • 3
  • 23
  • 40