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计算不会有边界问题.
- 再加一个月,并输出该月的一号,
- 再减一天就得到所要的月末日期.