Я получаю дату, которая представляет дату и время в utc. Скажем так:
21 июня 2019 г. 10:00
Я бы хотел перевести эту дату в часовой пояс "Европа / Вена", ожидая:
21 июня 2016 г. 12:00
Я не понимаю, почему мой код ниже показывает одинаковое время для обоих
Date utcFinish = new Date(new Date().getYear(), Calendar.JUNE, 21);
TimeZone europeVienna = TimeZone.getTimeZone("Europe/Vienna");
Calendar finishInViennaTime = Calendar.getInstance(europeVienna);
finishInViennaTime.setTime(utcFinish);
System.out.println(format.format(utcFinish));
System.out.println(format.format(finishInViennaTime.getTime()));
Выход:
2019-06-21 00:00
2019-06-21 00:00
Какое будет лучшее решение только для java7 (без joda, localdate pls) !? Спасибо
РЕДАКТИРОВАТЬ: Я также пытался:
SimpleDateFormat formatWithTimezone = new SimpleDateFormat("yyyy-MM-dd HH:mm");
formatWithTimezone.setTimeZone(TimeZone.getTimeZone("Europe/Vienna"));
SimpleDateFormat formatonly = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date utcDate = new Date(new Date().getYear(), Calendar.JUNE, 21);
System.out.println(formatonly.format(utcDate));
System.out.println(formatWithTimezone.format(utcDate));
Выход:
2019-06-21 00:00
2019-06-21 00:00
РЕШЕНИЕ
Спасибо за все решения. В итоге проблема была в часовом поясе по умолчанию. Вот мое текущее решение (дальнейшая обратная связь приветствуется!):
// Unfortunately this date has the wrong time zone (Local Time Zone),
// because Date assumes Local Time Zone the database stores timestamps
// in utc that's why I now convert to a datestring and reparse
Date finishTimeWrongTimeZone = new Date(new Date().getYear(), Calendar.JUNE, 21);
// in reality i call the db here like getFinishTime();
// get the plain date string without time shifting
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd HH:mm");
String dateWithoutTimeZone = formatter.format(finishTimeWrongTimeZone);
// add the timezone to the formatter and reinterpret the datestring
// effectively adding the correct time zone the date should be in
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String finishTime = null;
try {
Date dateWithCorrectTimeZone = formatter.parse(dateWithoutTimeZone);
// Convert to expected local time zone (europe/vienna)
formatter.setTimeZone(TimeZone.getTimeZone("Europe/Vienna"));
finishTime = formatter.format(dateWithCorrectTimeZone);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(finishTime);