I receive a date that represents a datetime in utc. Lets say: 21-Jun-2019 10:00
I'd like to convert this datetime to the timezone "Europe/Vienna" expecting: 21-Jun-2019 12:00
I do not understand, why my code below shows the same time for both
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()));
Output:
2019-06-21 00:00
2019-06-21 00:00
What would be the best java7 only (no joda, localdate pls) solution!? Thank you
EDIT: I also tried:
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));
Output:
2019-06-21 00:00
2019-06-21 00:00
SOLUTION
Thanks for all the solutions. In the end the problem was the default timezone. Here is my current solution (further feedback welcome!):
// 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);