X-Git-Url: https://zdv2.bktei.com/gitweb/BK-2020-03.git/blobdiff_plain/849106f7246e47bc077d7f3b8228cec717a8e63d..26f0533782d8c57fb95b8df4f55057edcbf17703:/unitproc/bkt-timeEpochNS diff --git a/unitproc/bkt-timeEpochNS b/unitproc/bkt-timeEpochNS new file mode 100644 index 0000000..c490ddf --- /dev/null +++ b/unitproc/bkt-timeEpochNS @@ -0,0 +1,53 @@ +#!/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.2.3 + # Input: arg1: 'date'-parsable timestamp string (optional) + # Output: Nanoseconds since 1970-01-01 + # Depends: date 8, cut 8, yell() + # Ref/Attrib: Force base 10 Bash arith with '10#'. https://stackoverflow.com/a/24777667 + local argTime timeCurrent timeInput timeEpochFloat timeEpochInt + local timeEpochNsFrac timeEpochNs + + argTime="$1"; + + # Get Current Time + timeCurrent="$(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 + timeInput="$timeCurrent"; + else + ## F: Time argument exists, validate time + if date --date="$argTime" 1>/dev/null 2>&1; then + ### T: Time argument is valid; use it + timeInput="$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 + timeEpochFloat="$(date --date="$timeInput" +%s.%N)"; # Save ssss.NNNNNNNNN + timeEpochInt="$(echo "$timeEpochFloat" | cut -d. -f1)"; # Get ssss + timeEpochNsFrac="$(echo "$timeEpochFloat" | cut -d. -f2)"; # Get NNNNNNNNN + timeEpochNs="$(( (10#"$timeEpochInt" * 10**9) + (10#"$timeEpochNsFrac") ))"; + echo "$timeEpochNs"; +} # 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 +# License: GPLv3+