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

相关推荐
一灰灰blog19 小时前
Jar包会自己消失?Excel会“记忆“数据?我遇到了两个灵异bug
java·spring boot·bug·excel
王家视频教程图书馆2 天前
修复服务端500相应,修复客户端上传文件.tmp 服务端接受不到文件bug
bug
qq_401700412 天前
Qt开发过程中遇到哪些经典的bug
qt·bug
0白露4 天前
关闭搜狗输入法右下角广告,可以适用于大多数应用系统通知的广告
windows·bug
一只自律的鸡4 天前
【Linux驱动】bug处理 ens33找不到IP
linux·运维·bug
Lichenpar6 天前
Springboot采用FastJson2作为MessageConverter时,配置的全局日期类型序列化转换BUG
java·开发语言·bug
Irene19917 天前
AI 找 bug 的局限性 和 Deepseek 优势明显
bug
癫狂的兔子7 天前
【bug】【Python】pandas中的DataFrame.to_excel()和ExcelWriter的区别
python·bug
癫狂的兔子8 天前
【BUG】【Python】【Spider】Compound class names are not allowed.
开发语言·python·bug
netkiller-BG7NYT8 天前
阿里云语音合成CosyVoice重大BUG被我发现了
bug