我有以下代码,我的目标将以毫秒为单位返回 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());
输出是
时区 ID 为:GMT;以毫秒为单位的时间:1332740915154
时区 ID 为:Europe/Helsinki;毫秒时间:1332740915154
为什么不同的时区以毫秒为单位给出相同的值?
我想如果它是 GMT+0
那么它应该是与本地时区不同的毫秒值。
最佳答案
Why different Timezone give SAME value in millisec?
因为这就是它的意思要做的。来自文档:
(Returns) the current time as UTC milliseconds from the epoch.
换句话说,它是 getTime
返回的 Date
中的值 - 它不依赖于时区。如果您想要取决于时区的值,请使用 Calendar.Get(Calendar.YEAR)
等。
Calendar.getTime()
和 Calendar.getTimeInMillis()
都返回代表日历中瞬间的值,这是独立的时区和日历系统。
关于Java:时区为什么不同的时区以毫秒为单位给出相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9867254/