我想找到一种方法来计算指定月份中一周的第一天的索引。下面的代码是我开始的代码:
public static int getFirstDayOfWeekInMonth(String month, int year)
return ;
例如,如果变量 month = October,year = 2019,则返回值应为 1,因为 10 月一周的第一天是星期二(Mon = 0,Tue = 1,Wed = 2 ...) .
我想创建一个与此类似的公式,但不是 1 月为 13 日,2 月为 14 日:https://en.wikipedia.org/wiki/Zeller%27s_congruence#Implementation_in_software
最佳答案
private static DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM", Locale.ENGLISH);
public static DayOfWeek getFirstDayOfWeekInMonth(String month, int year) {
Month m = Month.from(monthFormatter.parse(month));
LocalDate firstOfMonth = LocalDate.of(year, m, 1);
return firstOfMonth.getDayOfWeek();
}
我的导入是:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
让我们试试看:
DayOfWeek firstDayOfTheWeek = getFirstDayOfWeekInMonth("October", 2019);
System.out.println("First day of week of October 2019 is " + firstDayOfTheWeek);
输出是:
First day of week of October 2019 is TUESDAY
我很高兴为您提供 DayOfWeek
枚举而不是数字索引。它对程序员更友好(并且同样高效)。换句话说,我看不出你为什么要数字索引,但如果你坚持:
int dowIndex = firstDayOfTheWeek.getValue();
System.out.println("Index is " + dowIndex);
Index is 2
DayOfWeek
从 1 = 星期一到 7 = 星期日对天进行编号。此编号符合国际标准 ISO 8601,为避免混淆,我建议您也遵循它。如果您坚持使用从 0 开始的索引,只需减去 1。
编辑:
How can I change the code so that it accepts a lower-case input, like "sep"? … Just the abbreviation would be good for now.
以下版本的格式化程序接受月份缩写 (sep) 而不是完整的月份名称 (september),并且不关心大小写:
private static DateTimeFormatter monthFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MMM")
.toFormatter(Locale.ENGLISH);
用它来代替上面的那个。通过此更改尝试该方法:
DayOfWeek firstDayOfTheWeek = getFirstDayOfWeekInMonth("sep", 2019);
System.out.println("First day of week of sep 2019 is " + firstDayOfTheWeek);
First day of week of sep 2019 is SUNDAY Index is 7
进一步编辑:
If I want to accept both the full month name and the abbreviation, but also case-insensitive, how would I do that?
private static DateTimeFormatter monthFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("[MMMM][MMM]")
.toFormatter(Locale.ENGLISH);
在格式模式中,方括号包含可选部分。 MMMM
是完整的月份名称,因此 Java 首先尝试解析一个月份(例如,九月)。无论成功与否,它都会尝试解析缩写 (MMM
, sep)。如果只有一次尝试成功,则有一个月的时间,其余的与以前一样。
链接: Oracle tutorial: Date Time解释如何使用 java.time。
关于java - 如何找到指定月份的星期几的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57829898/