【问题标题】:How to find the index of the first day of the week in a specified month?如何找到指定月份的一周第一天的索引?
【发布时间】:2019-09-07 00:54:12
【问题描述】:

我想找到一种方法来计算指定月份中一周第一天的索引。下面的代码是我开始的:

public static int getFirstDayOfWeekInMonth(String month, int year)
    return ;

例如,如果变量月份 = 十月,年份 = 2019,则返回应为 1,因为 10 月的第一天是星期二(星期一 = 0,星期二 = 1,星期三 = 2...) .

我想创建一个与此类似的公式,但不是 1 月 13 日和 2 月 14 日:https://en.wikipedia.org/wiki/Zeller%27s_congruence#Implementation_in_software

【问题讨论】:

  • 既然 Wikipedia 页面描述了您需要做什么,我假设您在将月份名称转换为 3 到 14 之间的数字时遇到了问题,对吧?
  • 不要让你的代码基于维基百科的算法。该功能是内置的,使用它。 The LocalDate class 为您提供所需的一切。
  • 只是出于好奇,为什么 Zeller 公式中重新编号的月份如此困扰您?这很容易做到,而且效果很好。 (重新编号的目的是将闰日放在年末,这使得计算更容易。)

标签: java algorithm calendar


【解决方案1】:
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);

输出是:

2019 年 10 月的第一天是星期二

我很高兴为您提供DayOfWeek 枚举而不是数字索引。它对程序员更加友好(并且同样高效)。换句话说,我认为你没有理由需要一个数字索引,但如果你坚持:

    int dowIndex = firstDayOfTheWeek.getValue();
    System.out.println("Index is " + dowIndex);

索引为 2

DayOfWeek 将天数从 1 = 星期一到 7 = 星期日。此编号与国际标准 ISO 8601 一致,为避免混淆,我建议您也遵循它。如果您确实坚持使用从 0 开始的索引,则只需减去 1。

编辑:

如何更改代码以使其接受小写输入,例如 “九月”? ......现在只是缩写就可以了。

以下版本的格式化程序接受月份缩写 (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

进一步编辑:

如果我想同时接受完整的月份名称和缩写,但是 也不区分大小写,我该怎么做?

private static DateTimeFormatter monthFormatter = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern("[MMMM][MMM]")
        .toFormatter(Locale.ENGLISH);

在格式模式中,方括号包含可选部分。 MMMM 是完整的月份名称,因此 Java 首先尝试解析一个(例如,september)。无论成功与否,它都会尝试解析缩写(MMM, sep)。如果只有一次尝试成功,则有一个月的时间,其余的都照常进行。

链接: Oracle tutorial: Date Time 解释如何使用 java.time。

【讨论】:

  • 另外,有没有什么方法可以在不改变我使用的代码的情况下实现这一点?这意味着 getFirstDayOfWeekInMonth 返回一个 int 值。
  • 如果我想同时接受完整的月份名称和缩写,而且不区分大小写,我该怎么做?
猜你喜欢
  • 2020-12-08
  • 2019-04-24
  • 1970-01-01
  • 1970-01-01
  • 2011-11-24
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多