Update on 2022-11-02 15:07:26
Per info date
The fuzz in units can cause problems with relative items. For example, `2003-07-31 -1 month’ might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:
get_end_date_of_this_month(){
tmp=$(date -d"$1" +'%Y-%m-15')
first_day=$(date -d"$tmp 1 month" +'%Y-%m-01')
enddate=$(date -d "$first_day -1 days" +"%F")
echo $enddate
}
# exmaple
$ get_end_date_of_this_month 2016-02-03
2016-02-29
get_end_date_of_this_month 2016-01-31
2016-01-31
- 分析
- 先将给定的日期保留年月,日期赋值成15. 保证date的 month计算不会有边界问题.
- 再加一个月,并输出该月的一号,
- 再减一天就得到所要的月末日期.

本文介绍了一种通过调整日期到每月15日的方式,避免了直接使用模糊单位(如-1个月)带来的边界问题,从而更准确地计算出任意指定日期的上个月末日期。

2890

被折叠的 条评论
为什么被折叠?



