在 shell
中,经常要计算各种各样的日期,将平时常用的计算日期方法记录了下来
如有不对,请及时指正
日期格式化
将格式为 yyyyMMdd
的日期格式化为 yyyy-MM-dd
curr_date=20220130
curr_month_begin=`date -d "${curr_date}" "+%Y-%m-%d"`
获取当前日期
获取今天的日期,格式为 yyyyMMdd
curr_date=`date "+%Y%m%d"`
echo $curr_date
获取月初、月末系列
获取本月第一天
curr_date=20220130
curr_month_begin=`date -d "${curr_date}" "+%Y%m01"`
获取本月最后一天
思路:先获取本月第一天,接着求下月第一天,然后下月第一天减去一天
curr_date=20220130
curr_month_begin=`date -d "${curr_date}" "+%Y%m01"`
next_month_begin=`date -d "${curr_month_begin} +1 month" "+%Y%m01"`
curr_month_end=`date -d "${next_month_begin} -1 day" "+%Y%m%d"`
获取上个月第一天
思路:先获取本月第一天,然后减去一个月
curr_date=20220130
curr_month_begin=`date -d "${curr_date}" "+%Y%m01"`
pre_month_begin=`date -d "${curr_month_begin} -1 month" "+%Y%m%d"`
获取上个月最后一天
思路:先获取本月第一天,然后减去一天
curr_date=20220130
curr_month_begin=`date -d "${curr_date}" "+%Y%m01"`
pre_month_end=`date -d "${curr_month_begin} -1 day" "+%Y%m%d"`
获取天数系列
获取本月的天数
思路:求出当月最后一天,然后最后一天的数字即天数
curr_date=20220130
curr_month_begin=`date -d "${curr_date}" "+%Y%m01"`
next_month_begin=`date -d "${curr_month_begin} +1 month" "+%Y%m01"`
curr_month_end=`date -d "${next_month_begin} -1 day" "+%Y%m%d"`
curr_month_days=`date -d "${curr_month_end}" "+%d"`