解决linux系统求前N月月份的bug

日常工作中,需要获取某个日期(20240531)的前N个月,通常会写命令

date -d "20240531 last-month" '+%Y%m'

我期望得到202404 但是很意外:

经过几轮测试,发现只要月内天数超过30天,即所有大月,计算都会有问题,于是为了解决这个问题,特意写了一个shell函数,代码如下:

bash 复制代码
function getLastMonth(){
# 用户输入的日期
current_date="$1"
# 月份偏移量
pos_month="$2"
 获取当前年
current_year=$(date -d "$current_date" '+%Y')

# 当前月份
current_month=$(date -d "$current_date" '+%m')

# 计算新的月份
let "new_month = current_month - pos_month"

# 如果结果的月份小于1,则需要调整年份和月份
if [ $new_month -lt 1 ]; then
  # 计算去年的月份
  let "new_month += 12"
  let "current_year -= 1"
fi
# 格式化输出为yyyymm
lastM=$(date -d "${current_year}-${new_month}-01" '+%Y%m')
echo $lastM
}

函数调用示例 mylastMonth=`getLastMonth 20240531 6`

可以获得202311月份

相关推荐
wok15718 小时前
Git Bash 执行中文命令报错 127:MSYS 参数编码 bug 排查与修复
git·bug·bash
李永奉1 天前
杰理可视化SDK开发-【BUG】AC7006F8更换AC7006F6芯片添加双备份OTA升级功能报代码端空间不足问题
bug
结实的洋葱1 天前
为啥程序会有bug?
bug
stevenzqzq1 天前
解决复杂bug思路
bug
namexingyun2 天前
Scaling Law bug实战启示:从“虚胖“到“精瘦“的算力效率革命
开发语言·网络·人工智能·bug·ai编程
callJJ23 天前
Volta + Claude Code 在 Windows 上的路径 Bug 复盘
windows·bug
xsc-xyc24 天前
记一次RK3568搭建NAS BUG:开发板插上 USB 移动硬盘没反应
bug
放风铃的兔子25 天前
我把 5 个 Python bug 投进 CubeSandbox 当沙盘 —— 从 envd 协议反编译到一键 RED→GREEN
bug·issue
zh_xuan1 个月前
诡异Bug:输入框删除字符,却越删越多
android·bug
绘梨衣5471 个月前
采集基类设计遇到的描述符bug
爬虫·python·bug