简体   繁体   English

如何在java.sql.Timestamp中使用Joda-Time

[英]How to use Joda-Time with java.sql.Timestamp

I Have a prepared statement 我有一份准备好的声明

INSERT INTO mst(time) VALUES (?);

where time is of type Timestamp in a PostgreSQL database. 其中time是PostgreSQL数据库中Timestamp的类型。
I am inserting a Joda-Time DateTime object, or I should say I am trying to. 我正在插入一个Joda-Time DateTime对象,或者我应该说我正在尝试。 I can find no way to convert the DateTime object into a java.sql.Timestamp . 我找不到将DateTime对象转换为java.sql.Timestamp的方法 I have read the Joda-Time docs and see no reference to this. 我已经阅读了Joda-Time文档并且没有参考这个。

Thanks. 谢谢。

You can convert a Joda DateTime to a long (millis since the epoch) first, and then create a Timestamp from that. 您可以先将Joda DateTime转换为long(自纪元以来的millis),然后再创建一个Timestamp。

DateTime dateTime = new DateTime();
Timestamp timeStamp = new Timestamp(dateTime.getMillis());

JodaTime's DateTime constructor can handle this for you now. JodaTime的DateTime构造函数现在可以为您处理。 (I'm not sure if that was true when the question was posted, but it's a top Google result so I figured I'd add a newer solution.) (我不确定问题发布后是否属实,但这是谷歌的最高结果,所以我想我会添加一个更新的解决方案。)

There's a few API options: 有几个API选项:

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

Both options accept java.sql.Timestamp because it extends java.util.Date, but the Nanoseconds will be ignored (floored), because DateTime and Date only have millisecond resolution*. 这两个选项都接受java.sql.Timestamp,因为它扩展了java.util.Date,但是Nanoseconds将被忽略(floored),因为DateTime和Date只有毫秒级的分辨率*。 Without a specific timezone it will default to DateTimeZone.UTC. 如果没有特定的时区,它将默认为DateTimeZone.UTC。

<Didactic Mode> <教学模式>
"Resolution" is how many digits are provided. “分辨率”是提供多少位数。 "Precision" is how accurate the representation is. “精确度”是表示的准确程度。 For example, MSSQL's DateTime has millisecond resolution, but only ~1/3 of a second precision (DateTime2 has variable resolution and higher precision). 例如,MSSQL的DateTime具有毫秒级的分辨率,但只有1/3的精度(DateTime2具有可变分辨率和更高的精度)。
</Didactic Mode> </ Didactic Mode>

UTC Timestamp with Millisecond Resolution Example: 具有毫秒分辨率的UTC时间戳示例:

new DateTime(resultSet.getTimestamp(1));

If you're using TIMESTAMP WITH TIME ZONE in your database then you can't use java.sql.Timestamp, because it doesn't support time zones. 如果您在数据库中使用TIMESTAMP WITH TIME ZONE,则无法使用java.sql.Timestamp,因为它不支持时区。 You'll have to use ResultSet#getString and parse the string. 您必须使用ResultSet#getString并解析字符串。

Timestamp without Time Zone with Second Resolution Example**: 没有时区的时间戳和第二个分辨率示例**:

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

UTC Timestamp with Second Resolution Example**: 带有第二个分辨率示例的UTC时间戳示例**:

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

Timestamp with Time Zone (offset format) with Second Resolution Example**: 带时区的时间戳(偏移格式)和第二个分辨率示例**:

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

Bonus: DateTimeFormat#forPattern statically caches parsers by pattern so you don't have to. Bonus: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. 我通常建议在DBO模型中使用String,以使分辨率明确,避免生成中间对象。 (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. (2013-11-14 09:55:25是否等于2013-11-14 09:55:25.000?)我通常会尝试区分“数据库模型对象”优化数据保存问题和“业务模型对象”优化服务级别使用,其间包含转换/映射层。 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. 我发现基于CRUD的DAO直接生成业务对象往往会混淆优先级并优化两者,因为错过边缘情况而从意外的位置抛出异常。 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> </ 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. **时间戳字符串格式可能因数据库而异,但不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM