2

Hi I have a problem : from server I get a time and it looks like this :

"date":"2017-05-24T07:56:22Z"

But now in my local time is 09:56:22 how I can convert this ?

  • @freedev the op seems to be about the java time API when the duplicate is based on the legacy API. It's not 100% clear though. – assylias May 24 '17 at 08:18

1 Answers1

3

First you need to parse the date, for example:

Instant instant = Instant.parse("2017-05-24T07:56:22Z");

Assuming your time zone is correctly set, you can then simply use:

LocalTime localTime = instant.atZone(ZoneId.systemDefault()).toLocalTime();

If you want to use a specific time zone instead of the system default time zone:

LocalTime localTime = instant.atZone(ZoneId.of("Europe/London")).toLocalTime();
assylias
  • 321,522
  • 82
  • 660
  • 783
  • I don't have a method a instant.atZone –  May 24 '17 at 08:17
  • @PawełO What do you mean? It's [there](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#atZone-java.time.ZoneId-)... I've tested the code I provided and it compiles and run as expected. – assylias May 24 '17 at 08:19
  • I paste your code and I see : Cannot resolve method "atZone" –  May 24 '17 at 08:21
  • Have you pasted the two lines (`Instant instant = ...` AND `LocalTime localTime = ...`)? What version of Java are you using? – assylias May 24 '17 at 08:22
  • Java 7 and yes I pasted two lines –  May 24 '17 at 08:26
  • import org.joda.time.LocalTime; this I have to import ? –  May 24 '17 at 08:27
  • The solution I propose requires the Java time API, available in Java 8+. If you are using Joda Time you need to say so in your question and/or add the relevant tag to your question. – assylias May 24 '17 at 08:28
  • So can you tell my what I have to compile in gradle to use a Java time API ? –  May 24 '17 at 08:31
  • @PawełO it's part of Java 8, so you just need to set your source level to 1.8. That's assuming you are not developping for android. – assylias May 24 '17 at 08:33