Skip to content

Instantly share code, notes, and snippets.

@ruario
Created October 16, 2023 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruario/cbd29358bc71ba749b2b597a98701fd8 to your computer and use it in GitHub Desktop.
Save ruario/cbd29358bc71ba749b2b597a98701fd8 to your computer and use it in GitHub Desktop.
Show the current Decimal time or convert from "Standard time" to Decimal time
#!/bin/sh -eu
# Check for -s as an argument and if so convert decimal time to 'standard time'
if [ "${1-}" = '-s' ]; then
if [ -n "${2-}" ]; then
TIME_IN_SECS="$(echo 864*$(echo "$2" | tr -d :)/10 | bc)"
if [ "$(uname -s)" = Darwin ]; then
date -j -f "%s" "$(expr $(date -j -f '%H:%M:%S' '00:00:00' '+%s') + $TIME_IN_SECS)" '+%H:%M'
exit 0
else
date --date="0 today + $TIME_IN_SECS seconds" '+%H:%M'
exit 0
fi
else
echo "Provide a decimal time to convert" >&2
exit 1
fi
fi
# Check for -u as an argument and if so print the time for the IERS Reference Meridian (UTC equivalent)
if [ "${1-}" = '-u' ]; then
TIME_INPUT="$(date -u '+%H:%M:%S')"
shift 1
else
TIME_INPUT="$(date '+%H:%M:%S')"
fi
# Normalise any user provided time formatting provided
if [ -n "${1-}" ]; then
if echo "$1" | grep -q ':.*:' ; then
TIME_INPUT="$1"
elif echo "$1" | grep -q '[0-9]' ; then
TIME_INPUT="${1}:00"
fi
fi
# Convert 'standard time' to decimal time
CURRENT_MINSEC="${TIME_INPUT#*:}"
echo "(("${TIME_INPUT%%:*}" * 3600) + ("${CURRENT_MINSEC%:*}" * 60) + "${CURRENT_MINSEC#*:}") / 86.4" \
| bc | sed 's/^/00/' | tail -c4 | sed 's/\(.*\)\(..\)$/\1:\2/'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment