Java:时区为什么不同的时区以毫秒为单位给出相同的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9867254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:42:22  来源:igfitidea点击:

Java: Timezone why different timezone give same value in millisec

java

提问by user84592

I have following code, my target is going to return GMT+0time in millisec. But Why I always get my local timezone millisec?

我有以下代码,我的目标将以GMT+0毫秒为单位返回时间。但是为什么我总是得到本地时区毫秒?

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Calendar cal2 = Calendar.getInstance();
System.out.println("Time zone id is:"+cal.getTimeZone().getID()+";time in millisec:"+cal.getTimeInMillis());
System.out.println("Time zone id is:"+cal2.getTimeZone().getID()+";time in millisec:"+cal2.getTimeInMillis());

The output is
Time zone id is:GMT;time in millisec:1332740915154
Time zone id is:Europe/Helsinki;time in millisec:1332740915154

输出是
Time zone id is:GMT;time in millisec: 1332740915154
Time zone id is:Europe/Helsinki;time in millisec:1332740915154

Why different Timezone give SAME value in millisec?
I suppose if it is GMT+0then it should be different value in millisec against local time zone.

为什么不同的时区以毫秒为单位给出相同的值?
我想如果是,GMT+0那么它应该是与本地时区不同的毫秒值。

回答by Jon Skeet

Why different Timezone give SAME value in millisec?

为什么不同的时区以毫秒为单位给出相同的值?

Because that's what it's meantto do. From the documentation:

因为这就是它的目的。从文档:

(Returns) the current time as UTC milliseconds from the epoch.

(返回)从纪元开始的 UTC 毫秒的当前时间。

In other words, it's the value which would be in the Datereturned by getTime- it doesn't depend on the time zone. If you want values which depend on the time zone, use Calendar.Get(Calendar.YEAR)etc.

换句话说,它是Date返回值中的值getTime- 它不依赖于时区。如果您想要取决于时区的值,请使用Calendar.Get(Calendar.YEAR)等。

Both Calendar.getTime()and Calendar.getTimeInMillis()return values representing the instantin time within the calendar, which is independent of both time zone and calendar system.

双方Calendar.getTime()Calendar.getTimeInMillis()表示返回值瞬间日历,这是独立于时区和日历系统中的时间。

回答by zsxwing

The millisecof a Date object in Javais just the milliseconds since GMT+0 1970/01/01 00:00:00. It's independent of the Time Zone. Time Zone is a property to format the Date to a readable string.

millisecDate对象的Java的仅仅是因为毫秒GMT+0 1970/01/01 00:00:00。它独立于时区。时区是将日期格式化为可读字符串的属性。

回答by kandarp

getTimeInMillis() method return the current time as UTC milliseconds from the epoch. So, you are getting same milliseconds even both calendar object has different timezone.

getTimeInMillis() 方法返回当前时间作为 UTC 毫秒从纪元开始。因此,即使两个日历对象具有不同的时区,您也会获得相同的毫秒数。