66

我有一个准备好的声明

INSERT INTO mst(time) VALUES (?);

其中 time 是PostgreSQL数据库中的Timestamp类型。 我正在插入一个Joda-Time DateTime对象,或者我应该说我正在尝试。我找不到将 DateTime 对象转换为java.sql.Timestamp的方法。我已经阅读了 Joda-Time 文档,但没有看到对此的参考。

谢谢。

4

2 回答 2

90

您可以先将 Joda DateTime 转换为 long(自纪元以来的毫秒),然后从中创建时间戳。

DateTime dateTime = new DateTime();
Timestamp timeStamp = new Timestamp(dateTime.getMillis());
于 2009-07-01T23:31:20.530 回答
10

JodaTime 的 DateTime 构造函数现在可以为您处理这个问题。(我不确定问题发布时是否属实,但这是谷歌的顶级结果,所以我想我会添加一个更新的解决方案。)

有几个 API 选项:

public DateTime(Object instant);
public DateTime(Object instant, DateTimeZone zone);

这两个选项都接受 java.sql.Timestamp,因为它扩展了 java.util.Date,但纳秒将被忽略(下限),因为 DateTime 和 Date 只有毫秒分辨率*。如果没有特定的时区,它将默认为 DateTimeZone.UTC。

<教学模式>
“分辨率”是提供多少位数。“精度”是表示的准确程度。例如,MSSQL 的 DateTime 具有毫秒分辨率,但只有约 1/3 秒的精度(DateTime2 具有可变分辨率和更高的精度)。
</教学模式>

具有毫秒分辨率的 UTC 时间戳示例:

new DateTime(resultSet.getTimestamp(1));

如果您在数据库中使用 TIMESTAMP WITH TIME ZONE,则不能使用 java.sql.Timestamp,因为它不支持时区。您必须使用 ResultSet#getString 并解析字符串。

没有时区的时间戳和第二个分辨率示例**:

LocalDateTime dt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
    .parseLocalDateTime(resultSet.getString(1));

具有第二分辨率示例的 UTC 时间戳**:

DateTime dt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
    .parseDateTime(resultSet.getString(1));

带有时区的时间戳(偏移格式)和第二分辨率示例**:

DateTime dt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss Z")
    .parseDateTime(resultSet.getString(1));

奖励:DateTimeFormat#forPattern 按模式静态缓存解析器,因此您不必这样做。

<Didactic Mode>
I generally recommend using a String in your DBO model in order to make resolution explicit and avoid generating intermediate objects. (Is 2013-11-14 09:55:25 equal to 2013-11-14 09:55:25.000?) I generally try to distinguish between "database model objects" optimizing for data preservation concerns and "business model objects" optimizing for service level usage with a transformation/mapping layer in between. I find having CRUD based DAOs generating business objects directly tends to mix up the priorities and optimize for neither, throwing exceptions from unexpected places because of missed edge cases. Having an explicit transformation layer also allows you to add validation if necessary, like if you don't control the data source. Separating the concerns also makes it easier to test each layer independently.
</Didactic Mode>

* If you need to resolve to nanosecond resolution in your business model you'll have to use a different library.

** Timestamp String format may vary between databases, not sure.

于 2013-11-14T19:35:25.927 回答