Printing dates in linux time format

I am new to Linux. How to print and save the date in a given date range.

For example, I have startdate = 2013-03-01 and enddate = 2013-03-25; I want to print the entire date in this range.

Thanks in advance

+7
source share
5 answers

As long as the dates are in the format YYYY-MM-DD, you can compare them lexicographically and date to perform calendar arithmetic without conversion to seconds:

 startdate=2013-03-15 enddate=2013-04-14 curr="$startdate" while true; do echo "$curr" [ "$curr" \< "$enddate" ] || break curr=$( date +%Y-%m-%d --date "$curr +1 day" ) done 

With [ ... ] you need to avoid < to avoid confusion with the input redirection operator.

It has a start date stamp wart if it is greater than the end date.

+11
source

Alternative if you want "last" dates:

 echo {100..1} | xargs -I{} -d ' ' date --date={}' days ago' +"%Y-%m-%d" 

Obviously, it will not work for arbitrary date ranges.

+5
source

Use date to convert your dates to seconds, do some math and convert back:

 #/bin/bash dstart=2013-03-01 dend=2013-03-25 # convert in seconds sinch the epoch: start=$(date -d$dstart +%s) end=$(date -d$dend +%s) cur=$start while [ $cur -le $end ]; do # convert seconds to date: date -d@ $cur +%Y-%m-%d let cur+=24*60*60 done 

For more information on date options, see man date .

+2
source

Another option is to use dateseq from dateutils ( http://www.fresse.org/dateutils/#dateseq ):

 $ dateseq 2013-03-01 2013-03-25 2013-03-01 2013-03-02 2013-03-03 2013-03-04 2013-03-05 2013-03-06 2013-03-07 2013-03-08 2013-03-09 2013-03-10 2013-03-11 2013-03-12 2013-03-13 2013-03-14 2013-03-15 2013-03-16 2013-03-17 2013-03-18 2013-03-19 2013-03-20 2013-03-21 2013-03-22 2013-03-23 2013-03-24 2013-03-25 
0
source

Slightly improved version

 #!/bin/bash startdate=2013-03-15 enddate=2013-04-14 curr="$startdate" while true; do [ "$curr" \< "$enddate" ] || { echo "$curr"; break; } echo "$curr" curr=$( date +%Y-%m-%d --date "$curr +1 day" ) done 
0
source

All Articles