Java时区:为什么需要Offset [英] Java Timezone: why Offset is needed

查看:128
本文介绍了Java时区:为什么需要Offset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是这样的:

我在数据库和时区中以毫秒为单位节省时间。例如,以毫秒为单位的时间是 1223123123232 在长和时区是亚洲/加尔各答。我必须将它转换为非洲/阿斯马拉时区。

I am saving time in millisecond in database and the timezone.For example the time in milisecond is 1223123123232 in long and timezone is Asia/Calcutta. I have to convert it to Africa/Asmara timezone.

long l = 1223123123232l;
TimeZone tz = TimeZone.getTimeZone("Asia/Calcutta");
long tzOff = tz.getOffset(l);
java.util.Date d = new Date(l-tzOff);   // WHY THIS??
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("Africa/Asmara"));// required timezone
String s = df.format(d);
System.out.println(s);

要检查我的推荐:链接

我的问题是:


  1. 如果时区只是不同格式的时间表示(地理区域偏离GMT),为什么我需要从实际时间中减去偏移时间 (l-tzOff)

  2. 为什么我不能忽略数据库中保存的时区,只考虑我想要转换的时区约会?

类似于:

long l = 1223123123232l;
java.util.Date d = new Date(l);
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("Africa/Asmara"));// required timezone
String s = df.format(d);
System.out.println(s);

我的系统时区亚洲/加尔各答,我想将 Africa / Bujumbura 时区中的日期转换为欧洲/梵蒂冈时区。上面的代码是在这种情况下不工作?为什么会这样?

My system timezone is Asia/Calcutta, i want to convert a Date in Africa/Bujumbura timezone to Europe/Vatican timezone.The above code is not working in this case? Why this is so?

推荐答案

Java日期不知道时区。因此,如果我在纽约省下14H00,它将与巴黎的14H00不同,尽管毫秒值是相同的。您需要使用唯一引用来保存日期。人们经常选择GMT + 0。

Java dates do not know about time zones. Therefore, if I save 14H00 in New-York, it will not be the same 14H00 as in Paris, although the millisecond value is the same. You need to use a unique reference to save dates. People often chose GMT+0.

如果你需要检查时区的当地时间,你可以使用我开发的工具这里

If you need to check local time across timezones, you can use a tool I developed here.

回答你的问题:


  1. 时区不代表时间,它是时间的本地化。您减去偏移量的原因是为了确保所有时间都是根据相同的参考定义的。

  2. 因为您会得到错误的结果和错误的日期。

这篇关于Java时区:为什么需要Offset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆