2

I have the following piece of code.

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/YYYY HH:mm");
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2016);
cal.set(Calendar.MONTH, 11);
cal.set(Calendar.DAY_OF_MONTH, 31);
cal.set(Calendar.HOUR_OF_DAY, 22);
Date start = cal.getTime();
System.out.println(dateFormat.format(start));
cal.set(Calendar.YEAR, 2017);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 5);
Date end = cal.getTime();
System.out.println(dateFormat.format(end));

It prints:

31/12/2016 22:00
01/01/2016 05:00

I expect that the year of the second date is 2017. What is going on? I'm using Java 1.7.

Auberon
  • 665
  • 2
  • 7
  • 23
  • What is your `dateFormat` ? – Costi Ciudatu Dec 26 '16 at 13:02
  • 1
    I got `31-12-2016 22:00` and `01-01-2017 05:00` – Gurwinder Singh Dec 26 '16 at 13:02
  • 1
    I just ran your code and it seems fine, printed 2017, no problem. Can you update you code with the full version ? maybe something outside that can be influencing ? like thread ? – Josh Dec 26 '16 at 13:03
  • Updated the question with the used format. – Auberon Dec 26 '16 at 13:05
  • 2
    Why do people keep using `YYYY` instead of `yyyy` without knowing what `YYYY` does? Unbelievable. In other words: starting using a proper pattern for printing your date. – Tom Dec 26 '16 at 13:07
  • @Tom Because I didn't realise that was an option. Thanks to your very helpful comment, I went on to read the docs and I know understand my error. So thanks, I guess. – Auberon Dec 26 '16 at 13:10
  • Auberon, it is *always* important to read the documentation, especially when passing "stuff" into the a constructor or a method. Please remember that for the future. – Tom Dec 26 '16 at 13:15

2 Answers2

2

The correct date format should be dd/MM/yyyy HH:mm, not dd/MM/YYYY HH:mm, note the lower case y.

With that it works correctly.

From the docs:

y Year
Y Week year

Explanation of the difference between year and week year (from here):

A week year is a year where all the weeks in the year are whole weeks. [...] Basically, this guarantees that a program working on a week's data will not transition between years. [...] this also means that the beginning of the year may not start on the first of January.

Loris Securo
  • 7,538
  • 2
  • 17
  • 28
-1

This is working fine with the following dataFormat.

SimpleDateFormat dateFormat =  new SimpleDateFormat("MM/dd/yyyy hh:mm");
SujitKumar
  • 142
  • 1
  • 10
  • it's up to you. how you will take your date format pattern. i simply given an example, because you didn't mentioned the data format in your question. please have common sense. – SujitKumar Dec 26 '16 at 15:03