The Java8 equivalents in ZonedDateTime Calendar.DAY_OF_WEEK_IN_MONTH

I'm trying to check the Thanksgiving Day (Thursday, November 4).
My ZonedDateTime is 2019-11-23T08: 43: 14.699-07: 00 [ America / Los_Angeles]

 

How to use the Java 8 ZonedDateTime API to check whether at week 4 Thursday

In the calendar, we have Calendar.DAY_OF_WEEK_IN_MONTH to calculate the number of weeks in a month. Is there such content ZonedDateTime in?

I have to use this 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;
    }

ZonedDateTime how to accomplish this?

Best answer

What you need is a month of consistent weeks. The first week of the month alignment of the month from 1 to 7, thus contains the first Thursday of the month, regardless of whether the month is the beginning of the day of the week. the second week is the alignment of the month 8-14, and so on.

 

 

    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 November 28 this year, so the above summary test (November 23) will not print anything right day to try:

 

    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

Published 549 original articles · won praise 0 · Views 2415

Guess you like

Origin blog.csdn.net/weixin_44109689/article/details/103934390