From: Steven Baltakatei Sandoval Date: Tue, 7 Jul 2020 02:59:17 +0000 (+0000) Subject: feat(unitproc):timeEpochNS:Add date-string parsing feature X-Git-Tag: 0.3.0~49 X-Git-Url: https://zdv2.bktei.com/gitweb/BK-2020-03.git/commitdiff_plain/6ed44731ee993aba953a652ac71a57bc21ec1cf5?hp=--cc feat(unitproc):timeEpochNS:Add date-string parsing feature --- 6ed44731ee993aba953a652ac71a57bc21ec1cf5 diff --git a/unitproc/bktemp-timeEpochNS b/unitproc/bktemp-timeEpochNS index 8c0fb08..33006e5 100644 --- a/unitproc/bktemp-timeEpochNS +++ b/unitproc/bktemp-timeEpochNS @@ -1,23 +1,52 @@ #!/bin/bash # Desc: Get timestamp in nanoseconds +yell() { echo "$0: $*" >&2; } #o Yell, Die, Try Three-Fingered Claw technique +die() { yell "$*"; exit 111; } #o Ref/Attrib: https://stackoverflow.com/a/25515370 +try() { "$@" || die "cannot $*"; } #o timeEpochNS() { # Desc: Get epoch nanoseconds # Usage: timeEpochNS - # Version 0.1.2 - # Input: (none) + # Version 0.2.0 + # Input: arg1: 'date'-parsable timestamp string (optional) # Output: Nanoseconds since 1970-01-01 - # Depends: date 8 - local currentTime epochSeconds fracNanosec epochNanosec - currentTime="$(date +%s.%N)"; - epochSeconds="$(echo "$currentTime" | cut -d. -f1)"; - fracNanosec="$(echo "$currentTime" | cut -d. -f2)"; - epochNanosec="$(( ("$epochSeconds" * 1000000000) + ("$fracNanosec") ))"; - echo "$epochNanosec"; + # Depends: date 8, yell() + # Ref/Attrib: Force base 10 Bash arith with '10#'. https://stackoverflow.com/a/24777667 + local TIME_CURRENT TIME_INPUT TIME_EPOCH_FLOAT TIME_EPOCH_NSFRAC + local TIME_EPOCH_NS + + argTime="$1"; + + # Get Current Time + TIME_CURRENT="$(date --iso-8601=ns)"; # Produce `date`-parsable current timestamp with resolution of 1 nanosecond. + + # Decide to parse current or supplied time + ## Check if time argument empty + if [[ -z "$argTime" ]]; then + ## T: Time argument empty, use current time + TIME_INPUT="$TIME_CURRENT"; + else + ## F: Time argument exists, validate time + if date --date="$argTime" 1>/dev/null 2>&1; then + ### T: Time argument is valid; use it + TIME_INPUT="$argTime"; + else + ### F: Time argument not valid; exit + yell "ERROR:Invalid time argument supplied. Exiting."; exit 1; + fi + fi + # Construct and deliver nanoseconds since 1970-01-01 + TIME_EPOCH_FLOAT="$(date --date="$TIME_INPUT" +%s.%N)"; # Save ssss.NNNNNNNNN + TIME_EPOCH_INT="$(echo "$TIME_EPOCH_FLOAT" | cut -d. -f1)"; # Get ssss + TIME_EPOCH_NSFRAC="$(echo "$TIME_EPOCH_FLOAT" | cut -d. -f2)"; # Get NNNNNNNNN + TIME_EPOCH_NS="$(( (10#"$TIME_EPOCH_INT" * 1000000000) + (10#"$TIME_EPOCH_NSFRAC") ))"; + echo "$TIME_EPOCH_NS"; } # Nanoseconds since 1970-01-01 #==BEGIN sample code== echo "It's been $(timeEpochNS) nanoseconds since 1970-01-01."; +echo "It's been $(timeEpochNS "10 years ago") nanoseconds since 10 years ago."; +echo "It's been $(timeEpochNS "2003-02-01T08:59:15-05:00") nanoseconds since contact lost with STS-107."; #==END sample code== # Author: Steven Baltakatei Sandoval