1

I have a date as string: 2019-02-23T15:26:22.794624+05:30

Now I want to parse it to show my local time:

I used this code

SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSX");
sdf3.parse(dateFromServer)

Also tried setting timezone but nothing changed:

  sdf3.setTimeZone(TimeZone.getTimeZone("GMT"));

The output is :

Sat Feb 23 14:26:22 GMT+04:00 2019

Rather it should be :

Sat Feb 23 15:26:22 GMT+05:30 2019

Please help me understand this issue? Where I am doing wrong?

CodeGeek
  • 677
  • 2
  • 8
  • 22
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `OffsetDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Feb 23 '19 at 10:13
  • Cant use that because I am using this in android. and OffsetDateTime is supported for Java 8 which starts from Oreo. What if I want to have it for lower versions ? – CodeGeek Feb 23 '19 at 10:17
  • Your expectations are wrong. You are parsing into a `Date` and a `Date` hasn’t got an offset from UTC in it. Instead use `OffsetDateTime` (as already said). As the name says, it has. – Ole V.V. Feb 23 '19 at 10:17
  • 1
    Oh, you can. java.time has been backported and adapted for Android in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP). So if you add that library to your Android project and make sure you import `org.threeten.bp.OffsetDateTime`, you can use it. – Ole V.V. Feb 23 '19 at 10:19
  • Ok thank you. I will try to implement it – CodeGeek Feb 23 '19 at 10:23

0 Answers0