shell中獲取當前日期,下月1日,上月底,上月同期日期,比較兩個日期大小

在實際開發過程中會用到一些特定時間,請注意其中下月1日和上月同期日期無法用shell命令直接獲取,需做判斷

1.獲取系統當前時間
today=`date +%Y%m%d`
2.本月1日
firstday=`date -d "${today}" +%Y%m01`
3.本月月份
month=`date -d "${today}" +%m`
4.上月月底
l_lastday=`date -d "${firstday} last day" +%Y%m%d`
5.上月月份
l_month=`date -d "${l_lastday}" +%Y%m`
l_month2=`date -d "${l_lastday}" +%Y/%m`
6.下月1日
不能直接用n_month=`date -d "${today} +1 month" +%Y%m01`
當today=20190131時,用此公式n_month=20190301
需做判斷
n_month1=`date -d "$today +1 month" +%m`
n_month2=$[ $month + 1 ]
if [ $n_month2 -ge $n_month2 ]
then
n_month=`date -d "${today} +1 month" +%Y%m01`
else if [ $n_month2 -lt $n_month2 ]
then
n_month=`date -d "${today} +20 day" +%Y%m01`
fi
7.本月月底
MonthEnd=`date -d "$n_month -1 day" +%Y%m%d`
8.上月同期日期last_month_date
不可以直接用l_month_date=`date -d "$today -1 month" +%Y%m%d`
特殊情況時,不能取到正確的值,如today=20190331時,l_month_date=20190303,因爲3月有31天,2月只用28天,當today=20190331時,對應的上個月同期日期應該取2月份的最後一天。(在實際應用中計算績效時上月同期指標值會用到)
需用上月月底l_lastday和l_month_date做比較判斷:
先把日期轉換成時間戳格式,再進行比較:
t1=`date -d "$l_lastday" +%s`
t2=`date -d "$l_month_date" +%s`
if [ $t1 -ge $t2]
then
last_month_date=$l_month_date 
else
last_month_date=$l_lastday
fi
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章