如何设置java时区为UTC,如何在Java中转换UTC和本地时区

I am curious about timezone in Java. I want to get UTC time in milliseconds from a device and send to server. Server will convert it to local timezone when it displays time to users. Timezone in my system is Australia/Sydney( UTC + 11:00), and I have got the result below when I tested timezone:

int year = 2014;

int month = 0;

int date = 14;

int hourOfDay = 11;

int minute = 12;

int second = 0;

Calendar c1 = Calendar.getInstance();

c1.set(year, month, date, hourOfDay, minute, second);

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss z");

System.out.println(sdf.format(c1.getTime()));

Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

c2.set(year, month, date, hourOfDay, minute, second);

System.out.println(sdf.format(c2.getTime()));

output:

14/01/2014 11:12:00 EST

14/01/2014 22:12:00 EST

I thought I could have 13/01/2014 00:12:00 for c2 because UTC time is 11 hours later than mine. Does not Calendar work the way I expect?

Your help would be appreciated.

EDIT

Added z to display timezone. This makes me more confused because Mac says its timezone is (AEDT) Australian Eastern Daylight Time but Java is EST. Anyway still result is different because EST is UTC-5 hours.

解决方案

You probably meant to set the timezone on your formatter, not the Calendar (or in addition the the Calendar, it is not 100% clear what you mean to accomplish)! The timezone used to create the human representation comes from the SimpleDateFormat. All "timezone" information is lost from the Calendar when you convert it back into a java.util.Date by calling getTime().

The code:

Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

c2.set(year, month, date, hourOfDay, minute, second);

System.out.println(sdf.format(c2.getTime()));

is printing 14/01/2014 10:12:00 because 11AM UTC displayed in Syndey (the timezone of your formatter) is 10PM! (use HH in the format for 24 hour time)

This would print what it seems like you meant to do:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss z");

System.out.println(sdf.format(c1.getTime()));

sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

System.out.println(sdf.format(c1.getTime()));

The concept of 'UTC milliseconds' is meaningless. A quantity of milliseconds is just a fixed point in history, it has no timezone associated with it. We add a timezone to it to convert it into human-readable representations.

edit: Yes, the ambiguity of using 'EST' for both (US) Eastern Time and (Australian) Eastern Time has been a pitfall in Java since forever.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值