70. Converting between int and YearMonth
Consider that we have YearMonth.now()
and we want to convert it to an integer (for example, this can be useful for storing a year/month date in a database using a numeric field). Check out the solution:
public static int to(YearMonth u) {
return (int) u.getLong(ChronoField.PROLEPTIC_MONTH);
}
The proleptic-month is a java.time.temporal.TemporalField
, which basically represents a date-time field such as month-of-year (our case) or minute-of-hour. The proleptic-month starts from 0 and counts the months sequentially from year 0. So, getLong()
returns the value of the specified field (here, the proleptic-month) from this year-month as a long
. We can cast this long
to int
since the proleptic-month shouldn’t go beyond the int
domain (for instance, for 2023/2 the returned int
is 24277).
Vice versa can be accomplished as follows:
public static YearMonth from(int t) {
return YearMonth.of(1970, 1)
.with(ChronoField.PROLEPTIC_MONTH...