Search code examples
javadatetimejava-timedate-conversion

Wrong year in time conversion for final day of the year


The below code snippet prints the wrong year. Am I doing something wrong here? It prints the date time as 2018-12-31 00:00:00 but it should really be 2017-12-31 00:00:00. I converted the same epoch in JavaScript and it works fine. I also set the time zone as UTC and it gives the result as 2017-12-30 18:30:00 but setting the timezone as Asia/Calcutta increments it by a year. What am I missing here?

import java.time.*;
import java.time.format.*;
public class MyClass {
    public static void main(String args[]) {
        DateTimeFormatter format  = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");

        String time = LocalDateTime.ofInstant(Instant.ofEpochMilli(1514658600000L), ZoneId.of("Asia/Calcutta")).format(format);

        System.out.println(time);
    }
}

Solution

  • You need to use 'yyyy' instead of 'YYYY':

    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    From the docs :

    Symbol  Meaning                     Presentation      Examples
    y       year-of-era                 year              2004; 04
    Y       week-based-year             year              1996; 96