Skip to content

Instantly share code, notes, and snippets.

@theabbie
Last active June 20, 2025 09:34
Show Gist options
  • Save theabbie/e2ed0b813566a251c8e5d3f70df7a7bd to your computer and use it in GitHub Desktop.
Save theabbie/e2ed0b813566a251c8e5d3f70df7a7bd to your computer and use it in GitHub Desktop.
Terminal clock with NTP sync bash script
#!/bin/bash
tz_hours=0
tz_minutes=0
while [[ $# -gt 0 ]]; do
case "$1" in
-h) tz_hours="$2"; shift 2 ;;
-m) tz_minutes="$2"; shift 2 ;;
*) exit 1 ;;
esac
done
tz_offset_seconds=$((tz_hours * 3600 + tz_minutes * 60))
fetch_ntp() {
msg=$(printf '\x1b\0%.0s' {1..47})
response=$(echo -ne "$msg" | socat -T 2 - UDP:time.google.com:123 2>/dev/null)
[[ -z "$response" ]] && return
hex=$(echo -n "$response" | hexdump -v -e '1/1 "%02x"')
transmit_ts_hex=${hex:80:8}
ntp_seconds=$((16#${transmit_ts_hex}))
unix_seconds=$((ntp_seconds - 2208988800))
ntp_time=$unix_seconds
local_time=$(date +%s)
}
print_time() {
formatted=$(date -u -r "$1" "+%A, %d %B %Y at %I:%M:%S %p")
echo -e "\033[H\033[J$formatted"
}
fetch_ntp
count=0
while true; do
now=$(date +%s)
diff=$((now - local_time))
current=$((ntp_time + diff + tz_offset_seconds))
print_time "$current"
sleep 1
count=$((count + 1))
((count % 60 == 0)) && fetch_ntp
done
@theabbie
Copy link
Author

bash time.sh -h 5 -m 30

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment