天天看點

[Shell]date擷取指定日期的後幾天

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/SunnyYoona/article/details/51685280

1. 第一種方式

先把日期轉換為秒數,對這個秒數進行加減操作(加上或者減去幾天的秒數),在轉換為日期

  1. #! /bin/sh

  2. function nextDayOfDay2 {

  3. start=$1

  4. days=$2

  5. # 日期轉換為秒數

  6. seconds=`date -d $1 +%s`

  7. echo "日期秒數 -----> "${seconds}

  8. declare -i index

  9. index=0

  10. while [ ${index} -lt ${days} ]

  11. do

  12. total_seconds=$((seconds + ${index}*86400))

  13. date=`date -d @${total_seconds} +'%Y%m%d'`

  14. echo ${index}" ------> "${date}

  15. index=${index}+1

  16. done

  17. }

  18. nextDayOfDay2 $1 $2

列印從20160629号開始的連續5天日期:

  1. xiaosi@Qunar:~/company/sh$ bash date.sh 20160629 5

  2. 日期秒數 -----> 1467129600

  3. 0 ------> 20160629

  4. 1 ------> 20160630

  5. 2 ------> 20160701

  6. 3 ------> 20160702

  7. 4 ------> 20160703

2. 第二種方式
  1. #! /bin/sh

  2. function nextDayOfDay()

  3. {

  4. start=$1

  5. days=$2

  6. startDay=`date +'%Y%m%d' -d ${start}`

  7. echo "日期 -----> "${startDay}

  8. declare -i index

  9. index=0

  10. while [ ${index} -lt ${days} ]

  11. do

  12. date=`date -d "${startDay} ${index} days" +"%Y%m%d"`

  13. echo ${index}" ------> "${date}

  14. index=${index}+1

  15. done

  16. }

  17. nextDayOfDay $1 $2

  1. xiaosi@Qunar:~/company/sh$ bash date.sh 20160629 5

  2. 日期 -----> 20160629

  3. 0 ------> 20160629

  4. 1 ------> 20160630

  5. 2 ------> 20160701

  6. 3 ------> 20160702

  7. 4 ------> 20160703