Kay
Kay

Reputation: 2077

Find number of days from two dates using shell

I would like to find number of days from two given dates as 25 Aug 2017 and 05 Sep 2017.

My script:

start='2017-08-25';
end='2017-09-05';
ndays=(strtotime($end)- strtotime($start))/24/3600;
echo $ndays

When run this script, I am getting following error messages.

Line 3: syntax error near unexpected token `('

Desire output value:

10

Upvotes: 0

Views: 43

Answers (2)

chepner
chepner

Reputation: 532153

No shell that I am aware of has any tools for working with dates. At the very least, you need an external tool like date to convert your dates to an intermediate form, like the number of seconds since some fixed point in time (Unix uses Jan 1, 1970), then do your calculation with those values before processing the result further.

Assuming the use of GNU date from the Linux tag, you would do something like

start='2017-08-25'
end='2017-09-05'

start_seconds=$(date +%s --date "$start" --utc)
end_seconds=$(date +%s --date "$end" --utc)

ndays=$(( (end_seconds - start_seconds) / 24 / 3600 ));
echo $ndays

Note that since most shells only support integer arithmetic, this won't give you an exact number of days.

Upvotes: 2

choroba
choroba

Reputation: 242133

You can use date to convert each date to epoch seconds, then use arithmetic expansion to do the subtraction and conversion back to days:

#! /bin/bash
start='2017-08-25';
end='2017-09-05';

diff=$(date -d $end +%s)-$(date -d $start +%s)
echo $(( ($diff) / 60 / 60 / 24 ))  # 11

Upvotes: 1

Related Questions