Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print dates between two dates in format %Y%m%d in shell script?

Tags:

date

bash

shell

I have two arguments as inputs: startdate=20160512 and enddate=20160514.

I want to be able to generate the days between those two dates in my bash script, not including the startdate, but including the enddate:

20160513 20160514 I am using linux machine. How do I accomplish this? Thanks.

like image 212
buzzinolops Avatar asked May 13 '16 23:05

buzzinolops


People also ask

How do I print a date in dd mm yyyy format in Unix?

To format date in DD-MM-YYYY format, use the command date +%d-%m-%Y or printf "%(%d-%m-%Y)T\n" $EPOCHSECONDS .


3 Answers

Using GNU date:

$ d=; n=0; until [ "$d" = "$enddate" ]; do ((n++)); d=$(date -d "$startdate + $n days" +%Y%m%d); echo $d; done
20160513
20160514

Or, spread over multiple lines:

startdate=20160512
enddate=20160514
d=
n=0
until [ "$d" = "$enddate" ]
do  
    ((n++))
    d=$(date -d "$startdate + $n days" +%Y%m%d)
    echo $d
done

How it works

  • d=; n=0

    Initialize variables.

  • until [ "$d" = "$enddate" ]; do

    Start a loop that ends on enddate.

  • ((n++))

    Increment the day counter.

  • d=$(date -d "$startdate + $n days" +%Y%m%d)

    Compute the date for n days after startdate.

  • echo $d

    Display the date.

  • done

    Signal the end of the loop.

like image 156
John1024 Avatar answered Oct 26 '22 10:10

John1024


Another option is to use dateseq from dateutils (http://www.fresse.org/dateutils/#dateseq). -i changes the input format and -f changes the output format.

$ dateseq -i%Y%m%d -f%Y%m%d 20160512 20160514
20160512
20160513
20160514
$ dateseq 2016-05-12 2016-05-14
2016-05-12
2016-05-13
2016-05-14
like image 3
nisetama Avatar answered Oct 26 '22 10:10

nisetama


This should work on OSX, make sure your startdate is lesser than enddate, other wise try with epoch.

startdate=20160512
enddate=20160514

loop_date=$startdate

let j=0
while [ "$loop_date" -ne "$enddate" ]; do
        loop_date=`date   -j -v+${j}d  -f "%Y%m%d" "$startdate" +"%Y%m%d"`
        echo $loop_date
        let j=j+1
done
like image 2
Sanjeev Avatar answered Oct 26 '22 09:10

Sanjeev