Why is SimpleDateFormat parsing Date with wrong Month and Day? [duplicate]
Asked Answered
A

1

-2
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM DD HH:mm:ss z yyyy");
try {
      String d1 = list.get(position).getTaskTime(); //here d is "Tue Nov 06 15:37:51 EST 2016"
      date = sdf.parse(d);
      String d2=date.toString();
      Log.d("demo", d2); //here d2 is "Sat Jan 06 15:37:51 EST 2016"
  } catch (ParseException e) {
      e.printStackTrace();
     }

PS: I used Calendar class to add 10 months and made the date right which is kind of a hack but works. But, I want to know what's wrong with my code.

Arta answered 7/11, 2018 at 0:36 Comment(5)
Please don't link to an image. Instead, edit your question to show what the values are and how they're incorrect.Maritime
I posted here for the first time. I just used the available option. That link was generated by stackoverflow. Anyways, I updated the post. Thanks!Arta
Always search Stack Overflow thoroughly before posting.Baily
As an aside consider throwing away the long outmoded and notoriously troublesome SimpleDateFormat and friends, and adding ThreeTenABP to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with.Crosseye
It seems that getTaskTime( is returning a String where you ought to have a method to return a date-time object so you wouldn’t need to parse at all. Be the return type Date or Instant (I recommend the latter).Crosseye
B
3

DD is wrong. D is day of year. Sixth day of year is January 6.

You should use dd.

Docs: SimpleDateFormat

Bucella answered 7/11, 2018 at 0:40 Comment(1)
Thanks! I didn't know there's an alphabet to specify the day of an year. I assumed D to be the date. I knew it was some silly mistake but didn't know what.Arta

© 2022 - 2024 — McMap. All rights reserved.