Hello. I tried to figure out Java time zones, but I didn’t directly find what I needed. There is time in one time zone ("Atlantic / Azores"). You need to translate this into the current time zone of the user. Is it possible to somehow do this using standard methods without turning the bicycles in the code? Thank you in advance for your response.

  • one
    In java 8 added a new library of work with java.time time. For the line, there will be something like ZonedDateTime inLocalZone = ZonedDateTime.parse( "2016-04-12T00:00:00Z[Atlantic/Azores]" ).withZoneSameInstant( ZoneId.systemDefault() ) - zRrr

2 answers 2

 //исходное время ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Atlantic/Azores")); //в текущий часовой пояс ZonedDateTime withLocalZone = zdt.withZoneSameInstant(ZoneId.systemDefault()); //без зоны LocalDateTime localDateTime = withLocalZone.toLocalDateTime(); System.out.println(zdt); System.out.println(withLocalZone); System.out.println(localDateTime); 

conclusion

 2016-04-12T19:05:44.093Z[Atlantic/Azores] 2016-04-12T22:05:44.093+03:00[Europe/Moscow] 2016-04-12T22:05:44.093 
  • Thanks for the answer, but only now I realized that Android does not support the Java 8 libraries. Can I somehow get this result using older libraries? - ahgpoug
  • 2
    @ahgpoug Whereas in the next answer. You can also try to connect the Joda Time library (I did not try it myself, especially on the android). - Russtam
  • Ok, I'll try. Thanks for the answer. - ahgpoug

The internal representation of the date in java is stored in UTC, so it makes sense to transfer the date to the correct time zone when displaying to the user.

 // создаем Новый год на Азорских островах DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dfm.setTimeZone(TimeZone.getTimeZone("Atlantic/Azores")); Date d = dfm.parse("2016-01-01 00:00:00"); // будем выводить дату в ISO-формате DateFormat iso = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // дата на Азорских островах iso.setTimeZone(TimeZone.getTimeZone("Atlantic/Azores")); System.out.println(iso.format(d)); // 2016-01-01T00:00:00.000-0100 // местная дата iso.setTimeZone(TimeZone.getDefault()); System.out.println(iso.format(d)); // 2016-01-01T04:00:00.000+0300 

Ps. Everything you need to know about dates in Java

  • Something does not seem to be stored in UTC. Maybe one day. The other day, too, dealt with date-time. Vashche mess of some kind. In the netbeans debugger, if you look at Date, a bunch of fields open up. There is some kind of offset suspiciously coinciding with the difference in milliseconds of my time and UTC 28,800,000. Java is the 7th version. And everywhere they write that there is no timezone in Date. Lies - Sergey