gpt4 book ai didi

java - 如何仅使用 LocalDate 检查每月 13 日是否是星期五?

转载 作者:行者123 更新时间:2023-12-01 07:44:02 25 4
gpt4 key购买 nike

我想仅使用 LocalDate 来检查从 2019 年 1 月 1 日到 2029 年 12 月 12 日期间每月 13 日是否为星期五的情况。如何将 LocalDate.getDayOfMonth() 转换为 String 表示周一/周二/.../周六/周日?

    for (int i = 2019; i < 2030; i++) {
for (int j = 1; j < 13; j++) {
LocalDate date = LocalDate.of(i, j, 13);
int dayOfMonth = date.getDayOfMonth();


}
}

最佳答案

您可以使用enum java.time.DayOfWeek来检查它是否是星期五:

public static void main(String[] args) {
for (int i = 2019; i < 2030; i++) {
for (int j = 1; j < 13; j++) {
LocalDate date = LocalDate.of(i, j, 13);
DayOfWeek dayOfWeek = date.getDayOfWeek();

if (dayOfWeek == DayOfWeek.FRIDAY) {
System.out.println("Beware of bad luck in "
+ j + "/" + i + "…");
}
}
}
}

输出:

Beware of bad luck in 9/2019…
Beware of bad luck in 12/2019…
Beware of bad luck in 3/2020…
Beware of bad luck in 11/2020…
Beware of bad luck in 8/2021…
Beware of bad luck in 5/2022…
Beware of bad luck in 1/2023…
Beware of bad luck in 10/2023…
Beware of bad luck in 9/2024…
Beware of bad luck in 12/2024…
Beware of bad luck in 6/2025…
Beware of bad luck in 2/2026…
Beware of bad luck in 3/2026…
Beware of bad luck in 11/2026…
Beware of bad luck in 8/2027…
Beware of bad luck in 10/2028…
Beware of bad luck in 4/2029…
Beware of bad luck in 7/2029…

如果您想获取 DayOfWeekString 表示形式,您可以这样做:

String weekday = dayOfWeek.getDisplayName(TextStyle.FULL_STANDALONE, Locale.getDefault());

本例中选择的是系统默认Locale中使用的全名,在我的Locale中是"Freitag",但是您可以使用 Locale.US 或其他替代。

同样适用于java.time.Month,请参阅这个新的(但仅略有不同)示例:

public static void main(String[] args) {
for (int i = 2019; i < 2030; i++) {
for (int j = 1; j < 13; j++) {
LocalDate date = LocalDate.of(i, j, 13);
DayOfWeek dayOfWeek = date.getDayOfWeek();

// get the day of week as String (full name, US style)
String weekday = dayOfWeek.getDisplayName(TextStyle.FULL_STANDALONE, Locale.US);
// get the name of the Month as String (full name, US style)
Month month = Month.of(j);

if (dayOfWeek == DayOfWeek.FRIDAY) {
System.out.println("Beware of bad luck on "
+ weekday
+ " 13th, "
+ month.getDisplayName(TextStyle.FULL, Locale.US)
+ " "
+ i);
}
}
}
}

关于java - 如何仅使用 LocalDate 检查每月 13 日是否是星期五?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com