如何将 Timestamp 转换为 Date 或 DateTime 对象?

2022-01-13 00:00:00 datetime timestamp date jdbc java

我正在使用 ResultSet.getTimestamp() 从数据库中检索时间戳对象,但我想要一种简单的方法来获取 MM/DD/格式的日期YYYYHH:MM xx 格式的时间.我正在修补,看起来我可以通过使用 Java 中的 Date 和/或 DateTime 对象来做到这一点.这是最好的方法,还是我什至需要转换时间戳来完成这个?任何建议都会有所帮助.

I'm retrieving a timestamp object from a database using ResultSet.getTimestamp(), but I'd like an easy way to get the date in the format of MM/DD/YYYY and the time in a format of HH:MM xx. I was tinkering around, it it looks as though I can do such by making use of the Date and/or DateTime objects within Java. Is that the best way to go, or do I even need to convert the timestamp to accomplish this? Any recommendations would be helpful.

....
while(resultSet.next()) {
    Timestamp dtStart = resultSet.getTimestamp("dtStart");
    Timestamp dtEnd = resultSet.getTimestamp("dtEnd");

    // I would like to then have the date and time
    // converted into the formats mentioned...
    ....
}
....

推荐答案

java.sql.Timestampjava.util.Date.所以,只是向上吧.

java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");

使用 SimpleDateFormat 并创建 Joda DateTime 从现在开始应该是直截了当的.

Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.

相关文章