Skip to content

Instantly share code, notes, and snippets.

@jaymecd
Created May 6, 2021 21:18
Show Gist options
  • Save jaymecd/cb84abd1144418c5088c1449b15c29f5 to your computer and use it in GitHub Desktop.
Save jaymecd/cb84abd1144418c5088c1449b15c29f5 to your computer and use it in GitHub Desktop.
relative time in shell (awk)
#!/user/bin/env bash
# run as ./relative_time 2021-05-06T20:37:59Z
relative_time() {
declare -r dt="$1"
declare ts_then ts_now retval
! { ts1=$(date +%s -d "${dt}"); retval=$?; }
test "${retval}" -eq 0 || return
ts2=$(date +%s)
awk -v ts1="${ts1}" -v ts2="${ts2}" '
BEGIN {
diff = ts2 - ts1;
if (diff < 0) { print "not yet happened"; exit; };
if (diff > (24*60*60)) printf "%.0f days ago\n", diff/(24*60*60);
else if (diff > (60*60)) printf "%.0f hours ago\n", diff/(60*60);
else if (diff > 60) printf "%.0f minutes ago\n", diff/60;
else printf "%s seconds ago\n", diff;
}'
}
relative_time "$1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment