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

如何在Bash中基于指定日期获取过去n个月的首尾日期

在Bash中基于指定日期获取过去n个月的首尾日期

完全可以用Bash结合GNU date命令实现需求,以下是具体方案:

基础命令示例

1. 基于今日的日期计算

  • 当月首日:直接取当月1号
    date +'%Y-%m-01'
    
  • 当月最后日期:如果以今日为当月截止日,直接输出今日日期;如果要获取当月实际月末(不管当前日期),用下月首日减1天
    # 以今日为当月最后日期
    date +'%Y-%m-%d'
    # 获取当月实际月末
    date -d "$(date +'%Y-%m-01') +1 month -1 day" +'%Y-%m-%d'
    
  • 上月首日:
    date -d "-1 month" +'%Y-%m-01'
    
  • 上月月末:
    date -d "$(date -d "-1 month" +'%Y-%m-01') +1 month -1 day" +'%Y-%m-%d'
    

封装成通用函数

可以写一个函数,支持指定任意基准日期和过去的月数n,自动返回对应月份的首尾日期:

get_month_boundaries() {
    local target_date="$1"
    local n="$2"
    
    # 计算过去n个月的月份起始日期
    local first_day=$(date -d "$target_date -$n month" +'%Y-%m-01')
    
    # 确定最后日期:当月用基准日期,过去月份用月末
    local last_day
    if [ "$n" -eq 0 ]; then
        last_day=$(date -d "$target_date" +'%Y-%m-%d')
    else
        last_day=$(date -d "$first_day +1 month -1 day" +'%Y-%m-%d')
    fi
    
    echo "过去${n}个月:"
    echo "首日: $first_day"
    echo "最后日期: $last_day"
}

函数使用示例

# 基于今日,获取当月(n=0)的首尾日期
get_month_boundaries "$(date +'%Y-%m-%d')" 0

# 基于今日,获取上月(n=1)的首尾日期
get_month_boundaries "$(date +'%Y-%m-%d')" 1

# 基于指定日期2024-03-15,获取过去2个月(2024年1月)的首尾日期
get_month_boundaries "2024-03-15" 2

注意事项

  • 上述方案依赖GNU date,Linux系统默认自带;如果是macOS,需要先安装GNU coreutils(brew install coreutils),然后将命令中的date替换为gdate。
  • 日期计算会自动处理闰年、不同月份天数差异的问题,无需手动判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:40:37