【问题标题】:is there any easy way to get number of weekend in a month in java [duplicate]有没有简单的方法可以在java中获得一个月的周末数[重复]
【发布时间】:2019-11-15 07:26:29
【问题描述】:

我想从特定日期的特定月份查找周末数(这里的周末可能是一天或多天)。就像周末的数量是 2 (即星期六和星期日),而不是如何从 java 中的 2019-11-15 这样的日期计算周末的总数。

【问题讨论】:

  • 您能详细解释一下吗?如果一个月的第一天是星期日,那这算不算该月的第一天?
  • 你有没有尝试过?
  • 您应该在提问之前进行研究。包含您自己的努力也会更好,而不是简单地将您的需求倾倒在这里,让其他人代表您完成所有繁重的工作。
  • @GhostCatsaysReinstateMonica 为什么有人会赞成这个问题?这甚至没有意义。

标签: java date weekend


【解决方案1】:
public int weekendCount(int year, int month) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month - 1, 1);
    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    int cnt = 0;
    for (int i= 1; i<= daysInMonth; i++) {
        calendar.set(year, month - 1, i);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY) {
            cnt++;
        }
    }
    return cnt;
}

试试这个。

年-2019,月-11 输出=9

【讨论】:

  • java.util.Calendar 是 1999 年。
  • 我们正在设置年 - calendar.set(year, month - 1, 1);
猜你喜欢
  • 2021-06-28
  • 1970-01-01
  • 2011-04-20
  • 1970-01-01
  • 2011-08-29
  • 2012-01-05
  • 1970-01-01
  • 2011-03-02
  • 2012-02-08
相关资源
最近更新 更多