Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SimpleDateFormat shifts Date by one year [duplicate]

I'm getting very weird results, which I can not understand.

public class Test {

  private static DateFormat df = new SimpleDateFormat("dd.MM.YYYY HH:mm");

  public static void main(String[] args) {
    Date d = new Date(1356912000000L);
    System.out.println(d);
    System.out.println(df.format(d));
  }  
}

Gives the output:

Mon Dec 31 01:00:00 CET 2012
31.12.2013 01:00

I assume that this might be some issues with locales, but that's a shift by a whole year ! May anyone explain why it performs this way ?

like image 743
user1913596 Avatar asked Dec 14 '22 11:12

user1913596


2 Answers

YYYY is the week-year, not the calendar year. You want yyyy instead. Here's Java's relevant details:

Week Of Year and Week Year

Values calculated for the WEEK_OF_YEAR field range from 1 to 53. The first week of a calendar year is the earliest seven day period starting on getFirstDayOfWeek() that contains at least getMinimalDaysInFirstWeek() days from that year. It thus depends on the values of getMinimalDaysInFirstWeek(), getFirstDayOfWeek(), and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year (exclusive) are numbered sequentially from 2 to 52 or 53 (except for year(s) involved in the Julian-Gregorian transition).

The getFirstDayOfWeek() and getMinimalDaysInFirstWeek() values are initialized using locale-dependent resources when constructing a GregorianCalendar. The week determination is compatible with the ISO 8601 standard when getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4, which values are used in locales where the standard is preferred. These values can explicitly be set by calling setFirstDayOfWeek() and setMinimalDaysInFirstWeek().

A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values.

For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997 and their week year is 1997.

like image 162
Keith Avatar answered Dec 30 '22 18:12

Keith


Instead of:

"dd.MM.YYYY HH:mm"

Use:

"dd.MM.yyyy HH:mm"

like image 40
i23 Avatar answered Dec 30 '22 17:12

i23