【问题标题】:How to format Oracle's Interval Datatype to HH:MM format?如何将 Oracle 的间隔数据类型格式化为 HH:MM 格式?
【发布时间】:2020-07-27 08:24:37
【问题描述】:

我在 Oracle DB 中有一个表,下面是列

START_TIME INTERVAL DAY(0) TO SECOND(0)

我正在运行一个基本的选择查询来从数据库中获取值。我正在使用 JDBC 模板和 getString(),如下所示

String startTime = rs.getString("START_TIME");

当我在数据库中有 +00 11:00:00.000000 时,rs.getString("START_TIME") 获取 0 11:0:0.0

+00 09:30:00.000000 获取0 9:30:0.0 但我的要求是11:0009:30

有人可以帮助我如何进行这种格式化吗?

我已经尝试过以下方法:

How to represent Oracle Interval in Java - 但我正在为 DTO 使用基于 yaml 的 swagger 开放 API 生成,但不知道如何实现这一点。另外,我没有使用休眠。它是普通的 JDBC 模板。

My previous question - 但对我没有帮助

【问题讨论】:

标签: java sql oracle jdbctemplate


【解决方案1】:

您可以尝试以下变体之一:

// add this function: it converts intervalDS to Time/Timestamp
    public static Time intervalDStoTime(INTERVALDS intervalds) throws ParseException {
        SimpleDateFormat intervalFormat = new SimpleDateFormat("dd hh:mm:ss.SSS");
        java.util.Date parsedDate = intervalFormat.parse(intervalds.stringValue());
        Time time = new java.sql.Time(parsedDate.getTime());
        // or you can replace previous line with this one if yu will need timestamp:
        // Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
        return time;
    }

//...
// your code:
    //Original:
    oracle.sql.INTERVALDS startTime = rs.getINTERVALDS("START_TIME");
    System.out.println("Original:" + startTime);
    // 1: interval to time:
    Time time = intervalDStoTime(startTime);
    System.out.println("ToTime: " + time);
    // 2: + format
    System.out.println("ToTime + format: " + new SimpleDateFormat("hh:mm").format(time));
    // 3: format bytes
    byte[] bytes = startTime.toBytes();
    int hour = bytes[4] - 60;
    int minute = bytes[5] - 60;
    String hhmm = String.format("%02d:%02d", hour, minute);
    System.out.println("toBytes + format: " + hhmm);

【讨论】:

  • 谢谢,但是rs.getINTERVALDS("START_TIME"); 给出了编译问题The method getINTERVALDS(String) is undefined for the type ResultSet。如果它有效,您是否尝试过此代码?
  • 是的,当然,这是用实际的 oracle 驱动程序 19 测试的。您使用什么 oracle ojdbc 驱动程序?
  • @sudoss 你应该使用 OracleResultSet:docs.oracle.com/database/121/JAJDB/oracle/jdbc/…
  • 如何找到 ojdbc 驱动程序?如果您的意思是驱动程序类名,那么我使用的是oracle.jdbc.driver.OracleDriver
  • @sudoss 好的,然后将变量 rs 的 ResultSet 类型替换为 OracleResultSet
猜你喜欢
  • 1970-01-01
  • 2018-10-30
  • 2018-06-15
  • 2020-11-11
  • 2011-07-16
  • 1970-01-01
  • 2022-01-08
  • 2021-02-17
  • 2014-10-31
相关资源
最近更新 更多