]> zdv2.bktei.com Git - BK-2020-03.git/blob - unitproc/bkt-dateDuration
feat(unitproc/bkt-dateDuration):Count seconds between two dates
[BK-2020-03.git] / unitproc / bkt-dateDuration
1 #!/bin/bash
2
3 yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
4 die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
5 must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
6 dateDuration() {
7 # Desc: Given two date strings, output seconds duration
8 # Example: dateDuration 2012-06-30 2012-07-01 # Yields 86401 because leap second
9 # Version 0.0.1
10 # Depends: GNU Coreutils 9.4 (date, sed), GNU Bash 5.2.21
11 # References: [1] “"right" tz database (zoneinfo) files and GPS-based NTP” https://www.ucolick.org/~sla/leapsecs/right+gps.html
12
13 date1="$1";
14 date2="$2";
15 # Check args
16 if [[ -z "$date1" ]]; then die "FATAL:Invalid first date provided:${date1}"; fi;
17 if [[ -z "$date2" ]]; then die "FATAL:Invalid second date provided:${date2}"; fi;
18 if [[ $# -gt 2 ]]; then die "FATAL:Too many arguments."; fi;
19 ## Convert @-specified unix epoch into right unix epoch (rue)
20 re='@.*';
21 if [[ "$date1" =~ $re ]] || [[ "$date2" =~ $re ]]; then
22 die "FATAL:@-specified unix epoch detected. Why are you using me?";
23 fi;
24
25 # Use right unix epoch to account for leap seconds.
26 export TZ=right/UTC; # See [1]
27
28 # Convert date strings into Unix epoch
29 unixEpoch1="$(must date --date="$date1" +%s)";
30 unixEpoch2="$(must date --date="$date2" +%s)";
31
32 # Calculate duration
33 duration="$((unixEpoch2 - unixEpoch1))";
34 duration="$(sed -e 's/^-//' <<<"$duration"; )";
35
36 printf "%s\n" "$duration";
37 };
38
39 # Examples
40 dateDuration 2026-06-30 2026-07-01; # 86400 seconds
41 dateDuration 2012-06-30 2012-07-01; # 86401 seconds (leap second)