将java.sql.Timestamp转换为即时时间

时间:2018-06-22 10:39:41

标签: java date datetime instant sql-timestamp

我从数据库中检索到的值为:

20-DEC-17 10.15.53.000000000 AM

我希望将java.sql.Timestamp以上的日期转换为即时时间:

2017-12-20T10:15:53Z

我尝试使用当前时间戳记

Timestamp ts2 = new Timestamp(date1.getTime());
Date tradeDate1=new Date(ts2.getTime());
Instant tradeInstant = tradeDate1.toInstant();
System.out.println("Tade Instant"+ tradeInstant);
  • 实际时间戳记:Fri Jun 22 16:07:35 IST 2018
  • 什么是instan打印:Tade Instant2018-06-22T10:37:35.420Z

hours/mins/seconds是我不想要的更新-有没有办法可以保留原样?

3 个答案:

答案 0 :(得分:1)

我假设您至少使用Java 8和至少JDBC 4.2。我进一步假设时间戳记在数据库中没有时区或偏移量信息,但应理解为UTC中的时间戳记(建议做法)。在这种情况下,我认为最安全的方法是在Java中显式添加有关UTC偏移的信息:

PreparedStatement yourPreparedStatement 
            = yourConnection.prepareStatement("select trade_timestamp from your_table");
ResultSet rs = yourPreparedStatement.executeQuery();
while (rs.next()) {
    LocalDateTime tradeDateTime = rs.getObject(1, LocalDateTime.class);
    Instant tradeInstant = tradeDateTime.atOffset(ZoneOffset.UTC).toInstant();
    System.out.println("Trade Instant: " + tradeInstant);
}

请注意,该代码完全避免了过时的Timestamp类。 LocalDateTime是没有时区或偏移量的日期和时间。如果您的数据库数据类型为timestamp with timezone,则可以将Instant.class传递给rs.getObject并立即获得一个Instant,而不必进行转换。根据数据库及其功能,还可以将UTC设置为数据库会话的偏移量/时区,以便以相同的方式获得正确的时刻。

您的代码出了什么问题?

您的数据库会话似乎将时间戳理解为本地时区中的日期和时间(IST,我认为它是针对印度标准时间的(存在其他解释))。根据Mark Rotteveel的信息丰富的评论,此行为是JDBC所必需的,但是当该值采用UTC时,它并不符合您的需要。因此,尽管打印时看起来正确,但它给了您错误的时间点。转换本身是正确的。

答案 1 :(得分:0)

从关于不使用SimpleDateFormat的注释开始,我已移至DateTimeFormatter:

Date today = new Date();

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss") // same format
        .withLocale(Locale.UK) // UK locale
        .withZone(ZoneId.systemDefault());

String output = dateTimeFormatter.format( today.toInstant() );

System.out.println( output );

跑步给您:

2018-06-22T14:14:26

答案 2 :(得分:-1)

我创建了一个SimpleDateFormat,它只能打印“最多几秒钟”:

/* simple date format */   
DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

/* get toInstant() and convert to date */
Date myDate = Date.from(today.toInstant());

/* myDate formatted using DATE_FORMAT */
String formattedDate = DATE_FORMAT.format(myDate);

System.out.println(formattedDate);