calendar java 时区_java – 为什么Calendar使用正确的时区返回错误的小时?

返回的时间和日期是正确的,除了小时,比它应该小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

我的时区是东部标准时间,也就是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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值