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 和值 YearMonth。 YearMonth 类代表,嗯,一年零一个月。没有日期。正是您在问题中的目标。
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 ) ;