Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeFormatter not working all the time, bug?

I encountered a weird bug while running some code. Here is a simple version to showcase the same.

public class DateTest {

    public static void main(String[] args) {

        LocalDate decLast = LocalDate.of(2015, 12, 31);
        LocalDate novLast = LocalDate.of(2015, 11, 30);
        LocalDate octLast = LocalDate.of(2015, 10, 31);

        System.out.println(decLast+" "+novLast+" "+octLast);

        System.out.println(decLast.format(DateTimeFormatter.ofPattern("dd M YY"))+" "
                +novLast.format(DateTimeFormatter.ofPattern("dd M YY"))+" "
                +octLast.format(DateTimeFormatter.ofPattern("dd M YY")));


    }
}

This returned the following results

2015-12-31 2015-11-30 2015-10-31
31/12/16 30/11/15 31/10/15

Somehow, the 31st Dec 2015 was converted to 31st Dec 2016. I wrote a for loop to do the same for different years and found that there is variation in many years. The error doesn't exist for any dates below 26th December. Is this a bug or am I missing something here?

like image 634
mahacoder Avatar asked Jan 05 '16 13:01

mahacoder


1 Answers

The upper case Y is the "week based year", you are looking for the lower case y instead.

From the linked Wikipedia article (emphasis by me):

An ISO week-numbering year (also called ISO year informally) has 52 or 53 full weeks. That is 364 or 371 days instead of the usual 365 or 366 days. The extra week is referred to here as a leap week, although ISO 8601 does not use this term. Weeks start with Monday. The first week of a year is the week that contains the first Thursday of the year (and, hence, always contains 4 January). ISO week year numbering therefore slightly deviates from the Gregorian for some days close to 1 January.

[...]

For example, 29 December 2014 is ISO 2015-W1-1, i.e., it is in year 2015 instead of 2014.

Cf. also: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

like image 123
Marvin Avatar answered Oct 07 '22 22:10

Marvin