我正在尝试获取我的当地时间,当它是不同时区的午夜时。我的意思是:
- 伦敦的午夜时分,斯德哥尔摩几点钟了?
- 斯德哥尔摩几点钟,赫尔辛基午夜时分?
这是我的代码
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();
}
输出是:
London: 2013-04-12 13:00:00.000
Helsinki: 2013-04-12 23:00:00.000
我期望:
London: 2013-04-13 01:00:00.000
Helsinki: 2013-04-12 23:00:00.000
对于赫尔辛基来说,结果如预期,但对于伦敦来说,这是一个疯狂的结果,我不明白它来自哪里。
- - - 编辑 - - -
具有预期输出的最终代码:
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.");
输出:
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.