For performance reasons we want to limit the number of sub-process calls we need to invoke:
- use
bash
substring functionality to convert inputs into usable date/time strings
- use
bash
math to replace bc
call
bash
substring functionality to break the inputs into a usable date/time format, eg:
# convert to usable date/time format:
$ start_date=1996010100
$ echo "${start_date:0:4}-${start_date:4:2}-${start_date:6:2} ${start_date:8:2}:00:00"
1996-01-01 00:00:00
# convert to epoch/seconds:
$ start=$(date -d "${start_date:0:4}-${start_date:4:2}-${start_date:6:2} ${start_date:8:2}:00:00" +"%s")
$ echo $start
820476000
Applying to ${end_date}
and using bash
math:
$ end_date=1996010122
$ end=$(date -d "${end_date:0:4}-${end_date:4:2}-${end_date:6:2} ${end_date:8:2}:00:00" +"%s")
$ echo $end
820555200
$ hours=$(( (end - start) / 3600))
$ echo $hours
22
This leaves us with 2 sub-process calls ($(date ...)
). While other languages/tools (awk
, perl
, etc) can likely speed this up a bit, if you need to store the result in a bash
variable then you're looking at needing at least 1 sub-process call (ie, hours=$(awk/perl/??? ...)
).
If performance is really important (eg, needing to perform this 1000's of times) take a look at this SO answer that uses a fifo, background date
process and io redirection ... yeah, a bit more coding and a bit more convoluted but also a bit faster for large volumes of operations.