Date.toString() 显示什么时区?

2022-01-16 00:00:00 date timezone java

默认情况下,方法是什么时区 java.util.Date.toString() 显示?自 Java Date 将给定日期存储在 UTC 中,并且不包含任何明确的时区,Date.toString() 只显示主机的默认时区,或 TimeZone.getDefault()?

By default, what time zone does method java.util.Date.toString() display? Since a Java Date stores a given date in UTC and doesn't contain any explicit time zone, does Date.toString() simply display the default time zone for the host, or TimeZone.getDefault()?

推荐答案

它使用 TimeZone.getDefault() 显示,反过来,它将默认为其运行的操作系统的时区on(即主机).所以在实践中,它们是一样的

It displays using TimeZone.getDefault() which, in turn, will default to the time zone of the operating system it is running on (i.e. the host). So in practice, they will be the same thing

请注意,Java 日期并不是真正的日期!它是一个时间瞬间,由 纪元开始后的毫秒偏移量表示/em>.它仍然包含引用 year、month 等的方法,但这些方法都已弃用.您绝不应该像使用日期一样使用 Date 对象.

Note that a Java date is not really a date! It is an instant in time, represented by a millisecond offset since the beginning of the epoch. It still contains methods which reference year, month etc but these are all deprecated. You should on no account be using a Date object as if it were a date.

使用 Calendar(尽管这可能比 Date 更糟糕)或像 JODA 这样的体面的库.

Use a Calendar (although this is arguably even more broken than Date) or a decent library like JODA.

相关文章