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

我正在使用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... .... } .... 

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

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

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

 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)); } } 

您还可以从时间戳中获取DateTime对象,包括当前的夏令时:

 public DateTime getDateTimeFromTimestamp(Long value) { TimeZone timeZone = TimeZone.getDefault(); long offset = timeZone.getOffset(value); if (offset < 0) { value -= offset; } else { value += offset; } return new DateTime(value); }