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

相关推荐
福大大架构师每日一题12 分钟前
PyTorch v2.9.1 发布:重要 Bug 修复与性能优化详解
人工智能·pytorch·bug
黑臂麒麟1 小时前
Electron&OpenHarmony 跨平台实战开发(bug):npm 安装 Electron 依赖常见错误排查
electron·npm·bug·openharmony
CIb0la3 小时前
Complete Bug Bounty tool List for free
linux·运维·bug
欧恩意4 小时前
【Viusal Studio】关于增量链接机制
汇编·windows·bug
Austindatabases6 小时前
SQLite 开发中的数据库开发规范 --如何提升业务系统性能避免基础BUG
数据库·oracle·sqlite·bug·数据库开发
万粉变现经纪人21 小时前
如何解决 pip install 代理报错 407 Proxy Authentication Required 问题
windows·python·pycharm·beautifulsoup·bug·pandas·pip
爱尔兰极光1 天前
软件测试--BUG篇
bug·压力测试·测试
hadage2331 天前
windows alt + tab 切换窗口时会强制把我的中文键盘的中英文输入改为中文这个bug的曲线救国方式 da
bug
烧酒同学2 天前
【Qt】QScrollArea的滑动条无法拖动(已解决)
qt·bug
黎雁·泠崖2 天前
VS2022调试通关秘籍:变量跟踪+内存分析+bug定位
c语言·bug