0

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);
    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
guru107
  • 1,053
  • 1
  • 11
  • 28
  • 2
    `"YYYY-MM-dd HH:mm:ss"` should probably be `"yyyy-MM-dd HH:mm:ss"` – ernest_k Nov 18 '18 at 07:05
  • I tried your code both by using YYYY and by using yyyy It works good – Angelo Immediata Nov 18 '18 at 07:10
  • December 31, 2017 was a Sunday. In week schemes where Sunday is the first day of the week (e.g., in the USA), the week year will be 2018, that is, wrong. In the ISO week scheme used in many countries Monday is the first day of the week, so the week year of that Sunday will be 2017, that is, correct in this case. The format pattern string is still wrong and will give wrong results in other cases, Also @AngeloImmediata – Ole V.V. Nov 19 '18 at 08:29

1 Answers1

5

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
Nicholas K
  • 15,148
  • 7
  • 31
  • 57