如何将时间戳转换为Date或DateTime对象?

Kri*_*ouw 17 java datetime timestamp date jdbc

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

....
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...
    ....
}
....
Run Code Online (Sandbox Code Playgroud)

Chr*_*her 21

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp.getTime());

        // S is the millisecond
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");

        System.out.println(simpleDateFormat.format(timestamp));
        System.out.println(simpleDateFormat.format(date));
    }
}
Run Code Online (Sandbox Code Playgroud)


Bal*_*usC 15

java.sql.Timestamp是.的子类java.util.Date.所以,只是向上翻.

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Run Code Online (Sandbox Code Playgroud)

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

  • 如果将使用jodatime`DateTime dtStartDT = new DateTime(resultSet.getTimestamp("dtStart"));`就是所需要的. (12认同)