java 从 ZonedDateTime 获取一个月中的哪一天

java get which day of month from ZonedDateTime

我想从给定的 ZonedDateTime 中找出一个月中的哪一天。 我知道这一天是星期四,想找到每个月的哪个星期四? 例如:

执行此操作的简单方法是什么?

从该月中第一个出现的星期几开始,以 7 天的步长值循环遍历该月的所有日期,并不断递增计数器直到匹配给定日期。

演示:

import java.time.DayOfWeek;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(whichDowOfTheMonth("2021-06-10T13:30:30+03:00"));
        System.out.println(whichDowOfTheMonth("2021-06-17T13:30:30+03:00"));
        System.out.println(whichDowOfTheMonth("2021-06-24T13:30:30+03:00"));
    }

    static int whichDowOfTheMonth(String strDateTime) {
        ZonedDateTime zdt = ZonedDateTime.parse(strDateTime);
        DayOfWeek dow = zdt.getDayOfWeek();

        ZonedDateTime zdtFirstDowOfMonth = zdt.with(TemporalAdjusters.firstInMonth(dow));
        ZonedDateTime zdtLastDayOfMonth = zdt.with(TemporalAdjusters.lastDayOfMonth());

        int count = 1;
        for (ZonedDateTime date = zdtFirstDowOfMonth; !date.isAfter(zdtLastDayOfMonth); date = date.plusDays(7)) {
            if (date.equals(zdt))
                break;
            count++;
        }
        return count;
    }
}

输出:

2
3
4

ONLINE DEMO

Trail: Date Time.

了解有关现代日期时间 API 的更多信息
 private static int getWhicDayOfMonth(ZonedDateTime date) {
    return (date.getDayOfMonth() - 1) / 7 + 1;
 }

在你的例子中:

10 -> 2
17 -> 3
24 -> 4
31 (in some months) -> 5

或者简化为 date.getDayOfMonth() + 6) / 7 - 但我倾向于发现这更令人困惑

基本上与@ArvindKumarAvinash 提供的答案中的方法相同,但循环有点不同:

/**
 * <p>
 * Calculates which weekday of the month it is
 * in the {@link ZonedDateTime} passed.
 * </p>
 *  
 * @param zonedDateTime the datetime to calculate its "weekday of month"
 * @return the weekday of month
 */
private static int getWeekdayOfMonth(ZonedDateTime zonedDateTime) {
    // extract the values you are interested in from the datetime passed
    int dayOfMonth = zonedDateTime.getDayOfMonth();
    DayOfWeek dayOfWeek = zonedDateTime.getDayOfWeek();
    // provide a counter variable
    int weekdayCount = 0;
    // then iterate until the day of month and compare the days of week
    for (int d = 1; d <= dayOfMonth; d++) {
        if (zonedDateTime.withDayOfMonth(d).getDayOfWeek() == dayOfWeek) {
            // increase counter at every match (including the one passed)
            weekdayCount++;
        }
    }
    
    return weekdayCount;
}

你可以这样使用它:

public static void main(String[] args) {
    ZonedDateTime zdt = OffsetDateTime.parse("2021-06-17T13:30:30+03:00")
                                      .atZoneSameInstant(ZoneId.of(
                                                             "Europe/Istanbul"
                                                         )
                                      );
    System.out.println("The date "
                    + zdt.toLocalDate()
                    + " is "
                    + zdt.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH)
                    + " no. "
                    + getWeekdayOfMonth(zdt)
                    + " in "
                    + zdt.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH));
}

并收到回复

The date 2021-06-17 is Thursday no. 3 in June

在您的控制台中。