I get an array of such dates and times from the server,

String[] format = {"2017-01-27 00:00:00 +0000 UTC", "2017-01-27 22:00:00 +0000 UTC", "2017-01-27 15:00:00 +0000 UTC", "2017-01-27 19:00:00 +0000 UTC"}; 

How to get the current time and date in the application, convert this array with changes to the time zone that the user has.

  • Once again, from the very beginning, I did not understand anything that needs to be done! - JVic

2 answers 2

 final String[] format = { "2017-01-27 00:00:00 +0000 UTC", "2017-01-27 22:00:00 +0000 UTC", "2017-01-27 15:00:00 +0000 UTC", "2017-01-27 19:00:00 +0000 UTC" }; final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss Z"); for (int i = 0; i < format.length; i++) { try { System.out.println(dateFormat.parse(format[i])); } catch (final Exception e) { throw new RuntimeException("Unexpected data from server", e); } } 

In the constructor new SimpleDateFormat, you can slip the required locale, otherwise, Locale.getDefault(Locale.Category.FORMAT)

  • Thanks for the answer, and you can prompt after changing the date and time, can you somehow write it into an array, but {Fri Jan 27 03:00:00} like this without (+0000 UTC) and in Russian? - Serg

It is possible so:

 String[] dates = { "2017-01-27 00:00:00 +0000 UTC", "2017-01-27 22:00:00 +0000 UTC", "2017-01-27 15:00:00 +0000 UTC", "2017-01-27 19:00:00 +0000 UTC"}; DateTimeFormatter formatter = new DateTimeFormatterBuilder() .append(DateTimeFormatter.ISO_LOCAL_DATE) .appendLiteral(' ') .append(DateTimeFormatter.ISO_LOCAL_TIME) .appendLiteral(' ') .appendOffset("+HHmm", "0000") .appendLiteral(' ') .appendZoneId() .toFormatter(); for (String date : dates) System.out.println(ZonedDateTime .parse(date,formatter) .toInstant() .atZone(ZoneId.systemDefault()) .format(formatter)); 

The output will be:

2017-01-27 04:00:00 +04 Europe / Samara
2017-01-28 02:00:00 +04 Europe / Samara
2017-01-27 19:00:00 +04 Europe / Samara
2017-01-27 23:00:00 +04 Europe / Samara

  • I would add that your version only works with Java 8 - Sergi
  • And I would add that your example only works with java 1.2. But why this clarification? - Artem Konovalov
  • Unfortunately, not everyone has switched to 1.8 ... agree that hardly anyone is already working on 1.1 :) - Sergi
  • I always repelled by the fact that if the author of the question does not specify, then you can use any version. As for those who have not crossed, I can only sympathize with them - 1.9 is already on the nose. - Artem Konovalov
  • @ArtemKonovalov sorry but the DateTimeFormatter underlines in red - Serg