如何在Linux中获取排除周六周日的上月月末日期
问题描述
如何在Linux环境下获取排除周六和周日的上月月末日期?
例如:若当前日期为2023-01-07,上月月末日期应取2022-12-30(周五),而非2022-12-31(周六)。
当前已实现获取上月月末日期的代码(已修正语法错误):
export CurrentMonthStartDate=$(date -d "$(date '+%F')" '%Y-%m-01') export PreviousMonthStartDate=$(date -d "$CurrentMonthStartDate -1 month" "+%F") export PreviousMonthEndDate=$(date -d "$PreviousMonthStartDate +1 month -1 day" "+%F")
预期输出规则:
| current_date | expected output |
|---|---|
| 2023-02-04 | 2023-01-31 |
| 2023-03-06 | 2023-02-28 |
| 2023-04-03 | 2023-03-31 |
| 2023-05-08 | 2023-04-28 |
- current_date:任意格式为
YYYY-MM-DD的日期 - expected output:格式为
YYYY-MM-DD的上月月末日期 - expected output日期不得为
Saturday或Sunday
解决方案
在获取到上月末日期后,通过date命令的%u参数(返回1-7,对应周一到周日)判断该日期是否为周末,再做相应调整。
完整脚本代码
# 可替换为自定义日期,比如current_date="2023-01-07" current_date=$(date '+%F') # 获取上月第一天 current_month_start=$(date -d "$current_date" '%Y-%m-01') previous_month_start=$(date -d "$current_month_start -1 month" '+%F') # 获取上月最后一天 previous_month_end=$(date -d "$previous_month_start +1 month -1 day" '+%F') # 判断上月最后一天是星期几 day_of_week=$(date -d "$previous_month_end" '+%u') # 根据星期几调整日期 case $day_of_week in 6) # 周六,减1天 adjusted_end_date=$(date -d "$previous_month_end -1 day" '+%F') ;; 7) # 周日,减2天 adjusted_end_date=$(date -d "$previous_month_end -2 days" '+%F') ;; *) # 工作日,保持原日期 adjusted_end_date=$previous_month_end ;; esac echo "调整后的上月月末日期:$adjusted_end_date"
代码说明
- 自定义日期支持:如果不需要使用系统当前日期,直接把
current_date赋值为指定的YYYY-MM-DD格式日期即可。 - 周末判断逻辑:
- 若上月末是周六(
%u=6),日期减1天到周五 - 若上月末是周日(
%u=7),日期减2天到周五 - 工作日直接保留原日期
- 若上月末是周六(
- 格式一致性:全程使用
+%F格式输出,保证日期统一为YYYY-MM-DD。
验证示例
| current_date | 原上月末日期 | 星期几 | 调整后日期 | 符合预期 |
|---|---|---|---|---|
| 2023-01-07 | 2022-12-31 | 周六 | 2022-12-30 | 是 |
| 2023-02-04 | 2023-01-31 | 周二 | 2023-01-31 | 是 |
| 2023-03-06 | 2023-02-28 | 周二 | 2023-02-28 | 是 |
| 2023-04-03 | 2023-03-31 | 周五 | 2023-03-31 | 是 |
| 2023-05-08 | 2023-04-30 | 周日 | 2023-04-28 | 是 |
(注:原示例中2023-03-06对应的预期输出2023-03-28应为笔误,实际上月为2023年2月,月末为2023-02-28)
内容的提问来源于stack exchange,提问作者blackhole
相关产品推荐
相关产品推荐

