tl;dr
Map< String , YearMonth > map = … ;
map.put(
rs.getString( 3 ) , // key
YearMonth.from(
myResultSet.getObject( 2 , LocalDateTime.class )
) // value
);
Use objects, not text
Retrieve smart objects from your database rather than dumb text.
LocalDateTime
If your column is of a type akin to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE
, use java.time.LocalDateTime
.
Be aware that these types do not represent a moment as they purposely lack the context of a time zone or offset-from-UTC.
JDBC 4.2
JDBC 4.2 and later requires a JDBC driver to support the LocalDateTime
type.
Call the ResultSet#getObject
method rather than getString
.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
YearMonth
Change your map to a key of String
and a value of YearMonth
. The YearMonth
class represents, well, a year and a month. No day-of-month. Just what you are aiming for in your Question.
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 );
Generating text
Later, when you want to present that YearMonth
to the user as text in format of MM/YYYY, use DateTimeFormatter
to generate text.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/uuuu" ) ;
String output = myYearMonth.format( f ) ;