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

如何用Shell获取指定月份内与输入日期星期相同的所有日期

实现方案(GNU Date,适用Linux环境)

核心思路

不用前后循环遍历再筛选,直接通过当月首日的星期数和目标星期数计算出第一个匹配日期,之后每次累加7天直到超出当月最大天数即可,全程最多仅需迭代5次,性能更高。

完整代码

inputDate="2021/08/25"
# 提取目标星期(%u规则:1=周一,7=周日)
target_week=$(date -d "$inputDate" +%u)
# 提取输入日期的年、月
year_month=$(date -d "$inputDate" +%Y/%m)
# 计算当月第一天的星期
first_week=$(date -d "${year_month}/01" +%u)
# 计算第一个匹配日期的日数
offset=$(( (target_week - first_week + 7) % 7 ))
first_match=$(( 1 + offset ))
# 获取当月总天数
max_day=$(date -d "${year_month}/01 +1 month -1 day" +%d)
# 拼接结果
res=""
for (( d=first_match; d<=max_day; d+=7 )); do
    formatted_d=$(printf "%02d" $d)
    [ -z "$res" ] && res="${year_month}/${formatted_d}" || res="${res},${year_month}/${formatted_d}"
done

# 输出结果
echo $res

运行验证

输入inputDate="2021/08/25"时,输出结果和示例完全一致:2021/08/04,2021/08/11,2021/08/18,2021/08/25

macOS 适配说明

如果是macOS自带的BSD date,调整date命令的参数即可:

  • 日期解析命令替换为 date -j -f "%Y/%m/%d" "$inputDate" +%u
  • 相对日期计算调整为对应BSD格式即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:54:03