【问题标题】:How can I convert a Timestamp into either Date or DateTime object?如何将 Timestamp 转换为 Date 或 DateTime 对象?
【发布时间】:2011-11-21 11:42:45
【问题描述】:

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

【问题讨论】:

  • 没有DateTime 类与 Java 1 到 Java 9 捆绑在一起。

标签: java datetime date jdbc timestamp


【解决方案1】:

LocalDateTime dtStart = rs.getTimestamp("dtStart").toLocalDateTime();

将此 Timestamp 对象转换为代码 LocalDateTime。 转换会创建一个代码 LocalDateTime,它表示 同年、同月、同日、时、分、秒和纳秒 日期时间值作为此代码本地时区的时间戳。

从 1.8 开始

【讨论】:

    【解决方案2】:

    java.time

    现代答案:使用现代 Java 日期和时间 API java.time 进行日期和时间工作。早在 2011 年,使用 Timestamp 类是正确的,但从 JDBC 4.2 开始不再建议使用。

    对于您的工作,我们需要一个时区和几个格式化程序。我们不妨将它们声明为静态的:

    static ZoneId zone = ZoneId.of("America/Marigot");
    static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
    static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");
    

    现在的代码可以是例如:

        while(resultSet.next()) {
            ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                     .atZoneSameInstant(zone);
    
            // I would like to then have the date and time
            // converted into the formats mentioned...
            String dateFormatted = dtStart.format(dateFormatter);
            String timeFormatted = dtStart.format(timeFormatter);
            System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
        }
    

    示例输出(使用您提出问题的时间):

    日期:2011 年 9 月 20 日;时间:18:13 -0400

    在您的数据库中,建议将 timestamp with time zone 用于时间戳。如果这是您所拥有的,请像我在代码中所做的那样检索OffsetDateTime。在分别格式化日期和时间之前,我还将检索到的值转换为用户的时区。作为时区,我以 America/Marigot 为例,请提供您自己的时区。当然,如果您不想要任何时区转换,也可以省略。

    如果 SQL 中的数据类型只是没有时区的 timestamp,则改为检索 LocalDateTime。例如:

            ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                     .atZone(zone);
    

    无论细节如何,我相信你会为dtEnd 做类似的事情。

    我不确定HH:MM xx 中的xx 是什么意思。我只是将它留在格式模式字符串中,它以小时和分钟为单位生成 UTC 偏移量,不带冒号。

    链接: Oracle tutorial: Date Time 解释如何使用 java.time。

    【讨论】:

      【解决方案3】:

      您还可以从时间戳获取 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);
      }    
      

      【讨论】:

      • 这是什么DateTime 类?没有这样的类与 Java 捆绑在一起。您是否将 Joda-Time 添加到您的项目中?如果是这样,则无需将麻烦的旧旧日期时间类(如 Calendar)与 Joda-Time 混合,只需坚持使用 Joda-Time。此外,Joda-Time 项目现在处于维护模式,并建议迁移到现代 java.time 类。 java.time 类取代了旧的日期时间类(DateCalendar 等)和 Joda-Time。
      • DateTime 是 Joda-Time 的类。 OP 询问如何将时间戳转换为日期或日期时间。没错,这里不需要 Calendar 类。
      【解决方案4】:
      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));
          }
      }
      

      【讨论】:

      • 也许 "MM/dd/yyyy' 'HH:mm:ss:S" 更好?
      • 当然,分钟是“mm”,我更正了代码示例。
      【解决方案5】:

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

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

      从现在开始,使用 SimpleDateFormat 并创建 Joda DateTime 应该很简单。

      【讨论】:

      • 如果要使用 jodatime,只需 DateTime dtStartDT = new DateTime(resultSet.getTimestamp("dtStart"));
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-27
      • 2020-12-15
      • 2022-01-02
      • 1970-01-01
      • 2012-05-01
      相关资源
      最近更新 更多