Reputation: 1087
I have a two dates in date +"%Y%m%d%H%M%S" format. How to find the difference and how to check whether the difference is more than 4 hours? This is how i have tried
echo $(( ( $(date +"%Y%m%d%H%M%S") - $(date +"%Y%m%d%H%M%S" -d "1970-01-01 + $(stat -c '%Z' filename ) secs"))))
date command returns this
Sun Sep 6 10:35:19 CDT 2015
Upvotes: 1
Views: 1123
Reputation: 217
This shell function uses the GNU date utility to convert your date string to seconds since the epoch:
function dateconv() {
date --date=${1:0:4}-${1:4:2}-${1:6:2}T${1:8:2}:${1:10:2}:${1:12:2} +%s
}
It inserts hyphens, colons, and a T to convert it to the ISO 8601 format that date understands as an input format.
With that defined, you can do something like this to check the difference between two strings in variables d1 and d2:
if [ $(( $(dateconv $d2) - $(dateconv $d1) )) -gt 14400 ]
then
echo Difference is more than 4 hours
fi
It converts both date strings to seconds, subtracts them, and checks if the difference is more than 14400 seconds (4 hours).
Upvotes: 1