Reputation: 1103
I am trying to check Thanksgiving (4th Thursday of November).
I have ZonedDateTime
as 2019-11-23T08:43:14.699-07:00[America/Los_Angeles]
How do I check whether it is4th Thursday or not using java 8 ZonedDateTime
api
In calendar we have Calendar.DAY_OF_WEEK_IN_MONTH
to calculate the week number of in a month. Is there any such thing in ZonedDateTime
?
I have this using calendar.
// check Thanksgiving (4th Thursday of November)
if (cal.get(Calendar.MONTH) == Calendar.NOVEMBER
&& cal.get(Calendar.DAY_OF_WEEK_IN_MONTH) == 4
&& cal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
return false;
}
How can I achieve this using ZonedDateTime
?
Upvotes: 3
Views: 261
Reputation: 86203
What you need is the aligned week of month. The first aligned week of the month is from the 1 through the 7 of the month, so contains the first Thursday of the month no matter on which day of the week the month begins. The second aligned week is 8 through 14 of the month, etc.
ZonedDateTime zdt = ZonedDateTime.parse("2019-11-23T08:43:14.699-07:00[America/Los_Angeles]");
if (zdt.getMonth().equals(Month.NOVEMBER)
&& zdt.get(ChronoField.ALIGNED_WEEK_OF_MONTH) == 4
&& zdt.getDayOfWeek().equals(DayOfWeek.THURSDAY)) {
System.out.println("" + zdt + " is on Thanksgiving");
}
Since Thanksgiving is on November 28 this year, the above snippet testing November 23 doesn’t print anything. Try with the right day instead:
ZonedDateTime zdt = ZonedDateTime.parse("2019-11-28T17:34:56.789-07:00[America/Los_Angeles]");
2019-11-28T16:34:56.789-08:00[America/Los_Angeles] is on Thanksgiving
Upvotes: 2