简体   繁体   English

Calendar.DAY_OF_WEEK_IN_MONTH等效于java8中的ZonedDateTime

[英]Calendar.DAY_OF_WEEK_IN_MONTH equivalent in ZonedDateTime in java8

I am trying to check Thanksgiving (4th Thursday of November). 我想检查感恩节(11月的第四个星期四)。
I have ZonedDateTime as 2019-11-23T08:43:14.699-07:00[America/Los_Angeles] 我的ZonedDateTime2019-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 如何使用java 8 ZonedDateTime api检查是否是星期四

In calendar we have Calendar.DAY_OF_WEEK_IN_MONTH to calculate the week number of in a month. 在日历中,我们有Calendar.DAY_OF_WEEK_IN_MONTH来计算一个月的周数。 Is there any such thing in ZonedDateTime ? 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 ? 如何使用ZonedDateTime实现此ZonedDateTime

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. 该月的第一个对齐周是从该月的1到7,因此包含该月的第一个星期四,无论该月的哪一天开始。 The second aligned week is 8 through 14 of the month, etc. 第二个对齐的一周是本月的8到14,等等。

    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. 感恩节是在今年11月28日,上面的片段测试11月23日没有打印任何内容。 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 2019-11-28T16:34:56.789-08:00 [America / Los_Angeles]正在感恩节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM