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

如何获取2022年指定月份内特定星期几的日期

2022年指定月份特定星期几的日期生成方案

需求说明

需要找出2022年指定月份内,特定星期几对应的所有日期(例如2022年8月的星期六对应6日、13日、20日、27日)。

已有函数

已实现获取指定月份第一天星期数的C语言函数valid_dname(星期映射:周日=0、周一=1……周六=6):

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>

int valid_dname(char *md, char *m){
   struct tm   tm;
   int year = 2022;
    memset(&tm, 0, sizeof(tm));

    tm.tm_mday  = atoi(md);
    tm.tm_mon   = atoi(m); // 注意:tm_mon是0-based,1月传0,8月传7
    tm.tm_year  = year-1900;
    mktime(&tm);

    return tm.tm_wday;
}

当前卡点与解决方案

卡点描述

计划通过数组映射星期与初始日期(例如2022年8月的数组为[7,1,2,3,4,5,6],对应周日到周六),但不清楚如何循环处理后续日期的生成。

核心解决思路

  1. 用取模运算处理星期索引循环:利用一周7天的周期性,通过(索引差 +7) %7避免负数,计算每个星期对应的初始日期。
  2. 后续日期直接累加7:初始日期确定后,每次加7即可得到同星期的下一个日期,直到超过当月最大天数。

完整实现代码

int main() {
    // 配置参数:目标月份(0-based,7=8月)、目标星期几(6=周六)
    int target_month = 7;
    int target_weekday = 6;

    // 2022年各月天数(0=1月,平年无闰年)
    int month_days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
    int max_day = month_days[target_month];

    // 获取当月第一天的星期数
    int first_wday = valid_dname("1", "7"); // 8月第一天是周一,返回1

    // 初始化星期-初始日期映射数组(索引0=周日,6=周六)
    int wday_dates[7];
    for(int i = 0; i < 7; i++){
        // 计算当前星期与第一天星期的偏移量,加7避免负数取模
        int offset = (i - first_wday + 7) % 7;
        wday_dates[i] = 1 + offset;
    }
    // 此时wday_dates为[7,1,2,3,4,5,6],符合预期

    // 生成目标星期的所有日期
    printf("2022年%d月的所有星期六日期:\n", target_month + 1);
    int current_date = wday_dates[target_weekday];
    while(current_date <= max_day){
        printf("%d ", current_date);
        current_date += 7;
    }
    printf("\n");

    return 0;
}

代码说明

  • 取模运算的作用:(i - first_wday +7) %7确保偏移量始终为非负的0-6,完美适配一周7天的循环逻辑。
  • 当月最大天数:直接使用2022年平年的各月天数数组,比调用mktime更高效。
  • 后续日期生成:无需循环数组,直接对初始日期累加7即可,直到超过当月最大天数自动停止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:10:33