style(unitproc):validateInput():VAR_NAME to varName
[BK-2020-03.git] / unitproc / bktemp-timeEpochNS
1 #!/bin/bash
2 # Desc: Get timestamp in nanoseconds
3
4 yell() { echo "$0: $*" >&2; } #o Yell, Die, Try Three-Fingered Claw technique
5 die() { yell "$*"; exit 111; } #o Ref/Attrib: https://stackoverflow.com/a/25515370
6 try() { "$@" || die "cannot $*"; } #o
7 timeEpochNS() {
8 # Desc: Get epoch nanoseconds
9 # Usage: timeEpochNS
10 # Version 0.2.2
11 # Input: arg1: 'date'-parsable timestamp string (optional)
12 # Output: Nanoseconds since 1970-01-01
13 # Depends: date 8, yell()
14 # Ref/Attrib: Force base 10 Bash arith with '10#'. https://stackoverflow.com/a/24777667
15 local TIME_CURRENT TIME_INPUT TIME_EPOCH_FLOAT TIME_EPOCH_NSFRAC
16 local TIME_EPOCH_NS
17
18 argTime="$1";
19
20 # Get Current Time
21 TIME_CURRENT="$(date --iso-8601=ns)"; # Produce `date`-parsable current timestamp with resolution of 1 nanosecond.
22
23 # Decide to parse current or supplied time
24 ## Check if time argument empty
25 if [[ -z "$argTime" ]]; then
26 ## T: Time argument empty, use current time
27 TIME_INPUT="$TIME_CURRENT";
28 else
29 ## F: Time argument exists, validate time
30 if date --date="$argTime" 1>/dev/null 2>&1; then
31 ### T: Time argument is valid; use it
32 TIME_INPUT="$argTime";
33 else
34 ### F: Time argument not valid; exit
35 yell "ERROR:Invalid time argument supplied. Exiting."; exit 1;
36 fi;
37 fi;
38 # Construct and deliver nanoseconds since 1970-01-01
39 TIME_EPOCH_FLOAT="$(date --date="$TIME_INPUT" +%s.%N)"; # Save ssss.NNNNNNNNN
40 TIME_EPOCH_INT="$(echo "$TIME_EPOCH_FLOAT" | cut -d. -f1)"; # Get ssss
41 TIME_EPOCH_NSFRAC="$(echo "$TIME_EPOCH_FLOAT" | cut -d. -f2)"; # Get NNNNNNNNN
42 TIME_EPOCH_NS="$(( (10#"$TIME_EPOCH_INT" * 10**9) + (10#"$TIME_EPOCH_NSFRAC") ))";
43 echo "$TIME_EPOCH_NS";
44 } # Nanoseconds since 1970-01-01
45
46 #==BEGIN sample code==
47 echo "It's been $(timeEpochNS) nanoseconds since 1970-01-01.";
48 echo "It's been $(timeEpochNS "10 years ago") nanoseconds since 10 years ago.";
49 echo "It's been $(timeEpochNS "2003-02-01T08:59:15-05:00") nanoseconds since contact lost with STS-107.";
50 #==END sample code==
51
52 # Author: Steven Baltakatei Sandoval
53 # License: GPLv3+