【问题标题】:How do I convert a SQL date to String date in different format?如何将 SQL 日期转换为不同格式的字符串日期?
【发布时间】:2021-08-01 01:56:41
【问题描述】:

我有一个 SQL 查询结果,它以这种格式(“yyyy-MM-dd hh:mm:ss”)返回日期。我的要求是将其转换为字符串(MM/yyyy)并将其放入 Map 中以供进一步比较。我该如何继续这样做。到目前为止,这就是我所拥有的

  Map<String, String> postingDateAmountMap = new HashMap<>();
              postingDateAmountMap.put(rs.getString(3), rs.getString(2));

rs.getString(2) 返回日期为 2021-03-01 00:00:00,而我在地图中需要它为 03/2021。

注意:getString(3)getString(2) 是 ColumnIndex

提前致谢。

【问题讨论】:

    标签: java sql string date datetime


    【解决方案1】:

    tl;博士

    Map< String , YearMonth > map = … ;
    map.put( 
        rs.getString( 3 ) ,  // key
        YearMonth.from( 
            myResultSet.getObject( 2 , LocalDateTime.class )
        )                    // value
    );
    

    使用对象,而不是文本

    从您的数据库中检索智能对象而不是哑文本。

    LocalDateTime

    如果您的列的类型类似于 SQL 标准类型 TIMESTAMP WITHOUT TIME ZONE,请使用 java.time.LocalDateTime

    请注意,这些类型代表时刻,因为它们故意缺少时区上下文或与 UTC 的偏移。

    JDBC 4.2

    JDBC 4.2 及更高版本需要 JDBC 驱动程序来支持 LocalDateTime 类型。

    调用ResultSet#getObject 方法而不是getString

    LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
    

    YearMonth

    将您的地图更改为键 String 和值 YearMonthYearMonth 类代表,嗯,一年零一个月。没有日期。正是您在问题中的目标。

    Map< String , YearMonth > map = new HashMap<>();
    String k = rs.getString(3) ; // Named `k` for key of map entry.
    LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ; 
    YearMonth v = YearMonth.from( ldt ) ;  // Named `v` for value of map entry.
    map.put( k , v );
    

    生成文本

    稍后,当您想将 YearMonth 以 MM/YYYY 格式的文本呈现给用户时,请使用 DateTimeFormatter 生成文本。

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/uuuu" ) ;
    String output = myYearMonth.format( f ) ;
    

    【讨论】:

      【解决方案2】:

      嗨,RishiAutomation,您可以通过以下方法拆分为一行

      postingDateAmountMap.put(rs.getString(3), rs.getString(2).split("-")[1] + "/" + rs.getString(2).split("-")[0]);
      

      或如下两行

      String[] newDate = rs.getString(2).split("-");
      postingDateAmountMap.put(rs.getString(3), newDate[1] + "/" + newDate[0]);
      

      【讨论】:

      • 数据库可能有日期时间类型。 Java 在 java.time 中有出色的日期时间类。不需要字符串操作。
      猜你喜欢
      • 2015-07-13
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 2013-12-28
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多