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

问题描述

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

  • 2021-06-10T13:30:30+03:00 是 2. 星期四;

  • 2021-06-17T13:30:30+03:00 是 3. 星期四;

  • 2021-06-24T13:30:30+03:00 是上周四;

  • private static int getWhicDayOfMonth(zoneddatetime date) {
    
    }
    

有什么简单的方法可以做到这一点?

解决方法

 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 - 但我倾向于发现这更容易阅读

,

从当月中第一次出现星期几开始,以 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 了解有关现代 Date-Time API 的更多信息。

,

与@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

在您的控制台中。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...