P粉2855875902023-09-04 00:07:58
Your problem seems to stem from treating the year and month as separate values. Instead, combine them. Think in terms of years and months.
YearMonth
ClassJava contains a class for this concept. It's appropriately named: YearMonth
and is located in the java.time package.
YearMonth ym = YearMonth.of ( 2023 , 3 ) ;
Or use the Month
enumeration to ensure a valid value.
YearMonth ym = YearMonth.of ( 2023 , Month.MARCH ) ;
You can use map
. Use NavigableMap
to keep keys in sorted order.
NavigableMap< YearMonth , UUID > map = new TreeMap<>() ; map.put( YearMonth.of ( 2023 , Month.MARCH ) , UUID.randomUUID() ); map.put( YearMonth.of ( 2023 , Month.FEBRUARY ) , UUID.randomUUID() );
Test whether a value has been entered.
boolean alreadyPut2023March = map.containsKey( YearMonth.of ( 2023 , Month.MARCH ) ) ;
For text purposes, use the default ISO 8601 format: YYYY-MM
java.time classes use ISO 8601 format by default when parsing/generating text.
String iso8601Output = YearMonth.of ( 2023 , Month.MARCH ).toString() ;
Assuming that your database does not provide the year and month data type, such a string can be used to store in your database. I don't know of any database that provides this data type. So words are enough.
Please note that when sorting alphabetically, the values will also be sorted chronologically.
Your JSON will look like this:
{
"year-month": "2023-03",
"readingTime": "1"
}