返回的时间和日期是正确的,但小时的除外,该时间和日期应该比实际少1个小时。
我似乎正在设置获取正确的时间和日期所需的一切:
- I'm using Calendar.getInstance(), instead of new Date()
- I'm setting the timezone of the Calendar instance with Timezone.getTimeZone
- I'm using DateFormat and SimpleDateFormat to format the output
我的时区是
Eastern Standard Time
,又名UTC/GMT-5:00
。这些行均无效: - cal.setTimeZone(TimeZone.getTimeZone(cal.getTimeZone().getDisplayName()));
- cal.setTimeZone(TimeZone.getTimeZone("EST"));
- cal.setTimeZone(TimeZone.getTimeZone("UTC"));
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.setTimeZone(TimeZone.getTimeZone("GMT-5:00"));
...但是每个选项都设置了我想要的时区。
这是我的尝试,在这里我向
Calendar
实例错误地添加了1小时:PrintWriter output = null;
try {
output = new PrintWriter(
new BufferedWriter(new FileWriter("output.txt", true)));
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:ms MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
// ...doesn't seem to be working:
cal.setTimeZone(TimeZone.getTimeZone(cal.getTimeZone().getDisplayName()));
/*
* adding an extra hour here, to make up for the incorrect hour value???
* ...without this line, everything is correct except the hour = n - 1:
*/
//cal.setTimeInMillis(cal.getTimeInMillis() + (1000 * 60 * 60));
// printing to console here:
System.out.println(dateFormat.format(cal.getTime()));
System.out.println(cal.getTimeZone().getDisplayName());
// printing to the log-file here:
output.println(dateFormat.format(cal.getTime()));
output.println(cal.getTimeZone().getDisplayName());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}
输出:
10:05:43:543 10/10/2013
GMT-05:00
错误-应该是
11:05:43:543
! (p.s.-很遗憾,我无法使用Joda-Time) 最佳答案
1)在SimpleDateFormat中设置时区
2)使用UTC或“真实”时区,例如(“Austria/Vienna”);
(国家名称,以及时区中最大的城市都将查明)
EST(= UTC-5)不是非常适合计算目的的时区,因为它是没有夏令时的时间。
来自中欧的另一个例子:
在冬季,我们使用MEZ(CET),在夏季(夏时制),我们使用(MESZ = CEST)。
但是,您希望计算机为您进行计算,因此请不要使用它:
时区是地理弹性的,因此需要国家名称。
每个国家/地区都可以根据需要决定更改时区(例如,俄罗斯在一段时间前,西类牙正在讨论)。