You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取指定月份中某一特定星期几的出现次数?

获取指定月份中特定星期几的出现次数

通用计算逻辑

不用代码的话,你可以通过这两步快速算出结果:

  1. 确认目标月份的第一天是星期几,以及这个月的总天数。
  2. 分情况计算次数:
    • 如果第一天就是目标星期几:总天数≥29时出现5次,否则出现4次(28天刚好是完整4周)。
    • 如果第一天不是目标星期几:先算出当月第一个目标星期几的日期,再用(总天数 - 第一个目标日期) //7 +1得到最终次数。

举两个对应问题的实例:

  • 2023年1月:第一天是周日(目标星期几),总天数31≥29,所以周日出现5次。
  • 2023年2月:第一天是周三,第一个周二是7号,总天数28,(28-7)//7 +1 = 4,所以周二出现4次。

代码实现(Python)

用datetime模块封装成函数,直接传入年份、月份和目标星期几即可:

import datetime

def count_weekday_in_month(year, month, target_weekday):
    # target_weekday映射:0=周一,1=周二…6=周日(对应datetime.weekday()返回值)
    first_day = datetime.date(year, month, 1)
    first_weekday = first_day.weekday()
    
    # 计算当月总天数
    next_month = datetime.date(year, month+1, 1) if month !=12 else datetime.date(year+1, 1, 1)
    total_days = (next_month - first_day).days
    
    # 推算第一个目标星期几的日期
    delta = (target_weekday - first_weekday) %7
    first_target_day = 1 + delta
    
    if first_target_day > total_days:
        return 0
    return (total_days - first_target_day) //7 +1

# 测试:2023年1月星期日(对应target_weekday=6)
print(count_weekday_in_month(2023, 1, 6)) # 输出5
# 测试:2023年2月星期二(对应target_weekday=1)
print(count_weekday_in_month(2023, 2, 1)) # 输出4

代码实现(JavaScript)

用原生Date对象实现,注意月份是0-based(0代表1月),getDay()返回0=周日、1=周一…6=周六:

function countWeekdayInMonth(year, month, targetWeekday) {
    const firstDay = new Date(year, month, 1);
    const firstWeekday = firstDay.getDay();
    const totalDays = new Date(year, month+1, 0).getDate();
    
    const delta = (targetWeekday - firstWeekday +7) %7;
    const firstTargetDay = 1 + delta;
    
    if (firstTargetDay > totalDays) {
        return 0;
    }
    return Math.floor((totalDays - firstTargetDay)/7) +1;
}

// 测试:2023年1月星期日(对应targetWeekday=0)
console.log(countWeekdayInMonth(2023, 0, 0)); // 输出5
// 测试:2023年2月星期二(对应targetWeekday=2)
console.log(countWeekdayInMonth(2023, 1, 2)); // 输出4

内容的提问来源于stack exchange,提问作者Getting There

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 10:27:27