1

I am facing issue in java while date formatting. For all the other dates, this format is working fine. But for below date Thu Jan 06 03:30:51 IST 2022 when i use SimpleDateFormat I am getting below date as Output 2022-12-31T03:30:51 . Issue is Instead of year 2021 I am getting year as 2022

public static void main(String args[]) {
        DateFormat targetFormat = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
        Date date = new Date(122,0,6,3,30,51);//Thu Jan 06 03:30:51 IST 2022
        date = DateUtils.addDays(date, -6);//Fri Dec 31 03:30:51 IST 2021
        targetFormat.format(date);//2022-12-31T03:30:51 
    }

Please guide me

anonymous
  • 483
  • 2
  • 8
  • 24
  • 2
    It took me a while to notice your problem is that the year you're getting is 2022 instead of the expected 2011. You may want to [edit] your question and make that a bit more clear. – Federico klez Culloca Jan 10 '22 at 14:21
  • 4
    `Y` in the SimpleDateFormat class refers to `Week year`. See: https://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html - You probably want to use `y` (lower case) to get the normal year. – OH GOD SPIDERS Jan 10 '22 at 14:24
  • By the way, don't use `SimpleDateFormat` and `Date`. Use the newer classes from the `java.time` package. In your case probably `DateTimeFormatter` and `ZonedDateTime`. – MC Emperor Jan 10 '22 at 14:38

2 Answers2

0

You need to use new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);

"YYYY" is week-based calendar year.

"yyyy" is ordinary calendar year.

You can read this if you want to know more :

https://dev.to/shane/yyyy-vs-yyyy-the-day-the-java-date-formatter-hurt-my-brain-4527

Yiao SUN
  • 908
  • 1
  • 8
  • 26
0

If you use java 8 or higher, please don't use SimpleDateFormat and Date classes. They are badly outdated and SimpleDateFormat especially has a lot of nasty problems. See package java.time and read about it. As for your classes you will need to use DateTimeFormatter class and LocalDateTime class (or some other implementation of Temporal interface)

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • 1
    Ok, but how does this answer the question? They'll still need to write a pattern and they will write it with the same error even if they use a different API. – Federico klez Culloca Jan 10 '22 at 14:50