Difference between dates in hour in bash
How can I find the difference between two dates which are in the format
date +"%H-%M-%d-%m-%Y"And also I want the difference in hours. How can I find this using a single command.
41 Answer
If the dates are in a file a one-per-line, like, say:
16-49-24-02-2016
16-49-25-02-2016Then you could use awk:
awk -F- 'NR==1 { then = mktime(sprintf("%s %s %s %s %s 00", $5, $4, $3, $1, $2))
}
NR==2 { now = mktime(sprintf("%s %s %s %s %s 00", $5, $4, $3, $1, $2)); printf "%s\n", (now - then)/3600
}' input.txtThe mktime function expects time in YYYY MM DD HH MM SS, so we split the given timestamp and convert it to that format (using 00 for seconds). The difference between the timestamps is in seconds, so we divide by 3600 to get the hours.