I'm trying to get my local time, when it's midnight in a different timezone. What I mean is:
- What time is it in Stockholm, when it's midnight in London?
- What time is it in Stockholm, when it's midnight in Helsinki?
Here is the code I have
public static void main(String[] args) throws ParseException {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("Europe/Stockholm"));
Date date = formatter.parse("2013-04-13 00:00:00.000");
System.out.println("London: " + formatter.format(getFirstInstantOfDay("Europe/London", date)));
System.out.println("Helsinki: " + formatter.format(getFirstInstantOfDay("Europe/Helsinki", date)));
}
public static Date getFirstInstantOfDay(String timeZoneId, Date date) {
Calendar resultDate = Calendar.getInstance(TimeZone.getTimeZone(timeZoneId));
resultDate.setTime(date);
resultDate.set(Calendar.HOUR, 0);
resultDate.set(Calendar.MINUTE, 0);
resultDate.set(Calendar.SECOND, 0);
resultDate.set(Calendar.MILLISECOND, 0);
return resultDate.getTime();
}
The output is:
London: 2013-04-12 13:00:00.000
Helsinki: 2013-04-12 23:00:00.000
And I expected:
London: 2013-04-13 01:00:00.000
Helsinki: 2013-04-12 23:00:00.000
For Helsinki the result is as expected, but for London is this crazy result that I don't understand where it comes from.
----- EDIT -----
Final code with the expected output:
String dateStr = "2013-04-13";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
formatter.setTimeZone(TimeZone.getTimeZone("Europe/London"));
Date dateGB = formatter.parse(dateStr);
formatter.setTimeZone(TimeZone.getTimeZone("Europe/Stockholm"));
Date dateSE = formatter.parse(dateStr);
formatter.setTimeZone(TimeZone.getTimeZone("Europe/Helsinki"));
Date dateFI = formatter.parse(dateStr);
DateFormat stockholmFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
stockholmFormatter.setTimeZone(TimeZone.getTimeZone("Europe/Stockholm"));
System.out.println("Midnight in London is " + stockholmFormatter.format(dateGB) + " in Stockholm.");
System.out.println("Midnight in Stockholm is " + stockholmFormatter.format(dateSE) + " in Stockholm.");
System.out.println("Midnight in Helsinki is " + stockholmFormatter.format(dateFI) + " in Stockholm.");
Output:
Midnight in London is 2013-04-13 01:00:00.000 in Stockholm.
Midnight in Stockholm is 2013-04-13 00:00:00.000 in Stockholm.
Midnight in Helsinki is 2013-04-12 23:00:00.000 in Stockholm.