问题
I am using the recent java.time package and in particular the day of week getter of LocalDate.
I get a nice DayOfWeek enum when calling LocalDate.getDayOfWeek()
.
However, my code should be compatible with some older part of the application that uses the integer value of a Calendar weekday, i.e. obtained from the code Calendar.get(DAY_OF_WEEK)
.
Obviously, in the DayOfWeek enum, SUNDAY value is 7, and in Calendar DAY_OF_WEEK field, SUNDAY value is 1.
So, what choices do I have to convert one into another? Should I convert the LocalDate in java.util.Date and then into a Calendar?
回答1:
The WeekFields class exists for this purpose (used with LocalDate.get()):
int sundayBasedDow = date.get(WeekFields.SUNDAY_START.dayOfWeek());
来源:https://stackoverflow.com/questions/37795975/java-time-localdate-getdayofweek-to-java-util-calendar-getday-of-week