java.util.Date 是否使用 TimeZone? [英] Is java.util.Date using TimeZone?

查看:28
本文介绍了java.util.Date 是否使用 TimeZone?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两台不同的电脑,每台电脑都有不同的时区.

在一台计算机上打印System.currentTimeMillis(),然后在两台计算机上打印以下命令:System.out.println(new Date(123456)); --> 123456 代表计算机 #1 中 currentTimeMillis 中的数字.

第二次打印(虽然是硬编码的)会在两台计算机上产生不同的打印效果.这是为什么?

解决方案

一些迂腐的细节怎么样.

java.util.Date 是时区无关.在 javadoc 中说得对.

您想要关于特定时区的东西吗?那是 java.util.Calendar.>

棘手的部分?当你打印这些东西时(使用 java.text.DateFormat子类),即涉及日历(涉及时区).请参阅 DateFormat.setTimeZone().

它确实看起来(还没有检查实现)像 java.util.Date.toString() 经历了一个 DateFormat.因此,即使是我们(大部分)与时区无关的类也会被时区搞乱.

想要从我们纯粹的无区 Date 对象中获取时区内容吗?有 Date.toGMTString().或者您可以创建自己的 SimpleDateFormatter 并使用 setTimeZone() 来控制自己使用哪个区域.

I have 2 different computers, each with different TimeZone.

In one computer im printing System.currentTimeMillis(), and then prints the following command in both computers: System.out.println(new Date(123456)); --> 123456 stands for the number came in the currentTimeMillis in computer #1.

The second print (though typed hardcoded) result in different prints, in both computers. why is that?

解决方案

How about some pedantic detail.

java.util.Date is timezone-independent. Says so right in the javadoc.

You want something with respect to a particular timezone? That's java.util.Calendar.

The tricky part? When you print this stuff (with java.text.DateFormat or a subclass), that involves a Calendar (which involves a timezone). See DateFormat.setTimeZone().

It sure looks (haven't checked the implementation) like java.util.Date.toString() goes through a DateFormat. So even our (mostly) timezone-independent class gets messed up w/ timezones.

Want to get that timezone stuff out of our pure zoneless Date objects? There's Date.toGMTString(). Or you can create your own SimpleDateFormatter and use setTimeZone() to control which zone is used yourself.

这篇关于java.util.Date 是否使用 TimeZone?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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