将joda.time.DateTime转换为java.sql.Date并保留时区 [英] Convert joda.time.DateTime to java.sql.Date and retain time zone
问题描述
我有以下情况:
- Swing控件返回
日历
对象 - 中级
DateTime
我用来执行大量日期/时间操纵(joda)的对象 - 数据库连接(
OraclePreparedStatement
)只需要一个java.sql.Date
对象
- Swing control that returns a
Calendar
object - Intermediate
DateTime
object that I use to do heavy date/time manipulation (joda) - Database connection (
OraclePreparedStatement
) that only takes ajava.sql.Date
object
我的问题是, Calendar
和 DateTime
对象正好以格林尼治标准时间(我想要)显示日期,但是当我转换为 java.sql.Date
以发送到数据库时,日期将转换为当地时区。
My problem is that the Calendar
and DateTime
objects are properly displaying the date in GMT (which I want), but when I convert to java.sql.Date
in order to send to the database, the date is converted to the local time zone.
例如:
-
日历
和DateTime
是2012-08-13T23:59:59.000Z(正确的GMT) - 导致
java.sql.Date
是2012-08-14(本地UTC + 2日期不正确)
Calendar
andDateTime
are 2012-08-13T23:59:59.000Z (correct GMT)- Resulting
java.sql.Date
is 2012-08-14 (incorrect local UTC+2 date)
以下是我用来进行转换的代码。
Below is the code I'm using to do the conversion.
DateTime dateGmt = new DateTime(calendarGmt.getTimeInMillis(), DateTimeZone.UTC);
java.sql.Date sqlDate = new java.sql.Date(dateGmt.getMillis());
我不知道如何创建一个 java.sql.Date
对象,同时保留正确的时区。
I don't know how to create a java.sql.Date
object while retaining the correct time zone. It's also entirely possible that I'm doing an incorrect conversion.
推荐答案
java的内部表示.sql.Date
是1970年1月1日00:00 00:00之后的毫秒数。
The internal representation of a java.sql.Date
is the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.
您确定您没有看到 toString
问题吗?尽管折旧的方法 toGMTString()
仍然存在。
Are you sure that you're not looking at a toString
problem? The method toGMTString()
, although depreciated, still exists.
这篇关于将joda.time.DateTime转换为java.sql.Date并保留时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!