解决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月份

相关推荐
qq_452396234 小时前
【工程实战】第八篇:报告美学 —— Allure 深度定制:让 Bug 定位精准到秒
开发语言·python·bug
tkokof11 天前
捉虫(Bug)小记
人工智能·深度学习·bug·游戏开发
南宫萧幕1 天前
基于上一篇文章VMware+openweb UI+ollama+docker的bug问题总结
docker·容器·bug·openweb ui
呼啦啦5611 天前
测试(BUG篇)
bug
ZC跨境爬虫1 天前
3D地球卫星轨道可视化平台开发Day2(轨道错位Bug修复+模块化结构优化)
前端·3d·html·json·bug
柠檬07111 天前
记录bug :C++调用python 路径问题
c++·python·bug
初圣魔门首席弟子3 天前
bug20260415
c++·bug
万粉变现经纪人3 天前
如何解决 pip install flash-attention 报错 需要 SM_80+(Ampere)架构 问题
python·架构·django·bug·virtualenv·pip·pygame
zhanglianzhao4 天前
Gazebo仿真机器人和相机时Gazebo ROS Control 插件偶发性加载失败bug分析
机器人·bug·ros·gazebo·ros_control
techdashen4 天前
Go 1.25 新特性:Flight Recorder —— 像黑匣子一样捕捉线上 Bug
java·golang·bug