我有一个 Date 对象,它从数据库中获取已采用 UTC 格式的日期,但时区偏移量会根据应用程序运行的位置进行转换。
因此,如果数据库有日期:2019-09-06 00:00:00.000
并且应用程序在洛杉矶运行,Date 对象的偏移量将为 7,输出将如下所示 2019-09-06T07:00Z
。由于日期已经是 UTC 格式,我希望它看起来像 2019-09-06T00:00Z
无论它在哪里运行。
Date 类没有 setTimeZone()
方法,首先想到的是将其转换为字符串并硬编码 00:00Z
最后,这并不干净。有什么想法吗?
更多信息:该列的类型为 DATETIME。数据库:SQL Server。
最佳答案
I have a Date object that is getting the date from the database which is already in UTC,
不要。
糟糕的 Date
类在几年前就被现代的 java.time 类取代了。
您应该使用OffsetDateTime
从类型为TIMESTAMP WITH TIME ZONE
的数据库列中检索时刻。 .
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
该值可能采用 UTC 格式。如果您想查看调整为时区的时刻,请应用 ZoneId
来获取 ZonedDateTime
。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
but the timezone offset gets converted based on the location where the application is running.
请注意,虽然 java.util.Date
实际上是 UTC 中的一个时刻,但它的 toString
方法却说谎了。该方法在生成文本时动态应用 JVM 当前的默认时区。虽然本意是好的,但此反功能会造成 Date
中存在时区的错觉。
如果您仅使用java.time类,则不会出现此类问题。无需再次使用 java.util.Date
、java.sql.Date
、Calendar
、GregorianCalendar
>、SimpleDateFormat
、DateFormat
或其他此类遗留类。
So if the database has date: 2019-09-06 00:00:00.000 and the application is running in LA, the Date object will have the offset of 7 and the output will look like this 2019-09-06T07:00Z
这部分对我来说毫无意义。
您的数据库中的数据类型正确吗? TIMESTAMP WITHOUT TIME ZONE
将是跟踪时刻的错误类型。此类型只有日期和时间,但缺少相对于 UTC 或时区的偏移量的上下文。此类型不能代表时间轴上的特定点。
编辑您的问题以准确指定您的列是什么数据库以及什么数据类型。
至少尝试使用java.time来消除Date::toString
注入(inject)不适当时区的困惑。
The Date class does not have a setTimeZone() method
java.util.Date
始终采用 UTC,只是自 UTC 1970 年第一个时刻 1970-01-01T00:00:00Z 以来的毫秒数。而已。 (实际上还有更多,一个深埋的时区,没有 getter 方法,它会影响 equals 等的行为,但与我们这里的讨论无关。这个类是一团糟糕的设计。 )
and the first thing that came to mind is to convert it to a String and hardcode 00:00Z at the end, which isn't clean. Any ideas?
不,你绝对不应该玩这样的游戏。你只会陷入更深的麻烦。直接在数据库中获取数据类型,仅使用 Java 中的 java.time 类,您的问题就会得到解决。
由于您没有提供足够的详细信息,我无法提供进一步的帮助。搜索 Stack Overflow 以了解更多信息。这个话题已经被讨论过很多次了。
关于java - 如何更改 Java 中 Date 对象的时区偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070339/