Skip to content

Instantly share code, notes, and snippets.

@brianm
Last active September 13, 2018 17:37
Show Gist options
  • Save brianm/06b9b7221822bdf16555dc0c7e335b61 to your computer and use it in GitHub Desktop.
Save brianm/06b9b7221822bdf16555dc0c7e335b61 to your computer and use it in GitHub Desktop.
#! /bin/bash
set -e
# Requires WT_GOOGLE_API_KEY be set to a valid Google API Key
# That means, it needs to have both timezone API and geocoding API enabled
# https://developers.google.com/maps/documentation/timezone/get-api-key
# https://console.developers.google.com/apis/credentials
if [ "$#" -lt 1 ] || [ -z "$WT_GOOGLE_API_KEY" ]; then
echo "Usage: $(basename $0) LOCATION" >&2
echo ""
echo "Will lookup the current time at LOCATION"
echo ""
echo "Requires environment variable WT_GOOGLE_API_KEY be set."
echo ""
echo "To get an API key, see https://developers.google.com/maps/documentation/timezone/get-api-key"
echo "To ensure it has needed permissions, use https://console.developers.google.com/apis/credentials"
echo "WT_GOOGLE_API_KEY needs to have both timezone API and geocoding API enabled"
echo ""
exit 1
fi
# https://gist.github.com/cdown/1163649
urlencode() {
# urlencode <string>
old_lc_collate=$LC_COLLATE
LC_COLLATE=C
local length="${#1}"
for (( i = 0; i < length; i++ )); do
local c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-]) printf "$c" ;;
*) printf '%%%02X' "'$c" ;;
esac
done
LC_COLLATE=$old_lc_collate
}
KEY=$(urlencode $WT_GOOGLE_API_KEY)
TARGET=$(urlencode "$*")
URL="https://maps.googleapis.com/maps/api/geocode/json?key=$KEY&address=$TARGET"
LATLONG=$(curl -s $URL | jq '.results[0].geometry.bounds.northeast | "\(.lat),\(.lng)"' | sed 's/\"//g')
TIMESTAMP=$(date +%s)
ZONE=$(curl -s "https://maps.googleapis.com/maps/api/timezone/json?key=$KEY&location=$LATLONG&timestamp=$TIMESTAMP" | jq .timeZoneId | sed 's/\"//g')
TZ=$ZONE date
@brianm
Copy link
Author

brianm commented Sep 13, 2018

Script to use Google Geocoding API and Timezone API to find current time at an arbitrary location (one which Google can find via Geocoding API).

Requires an API key be set as an env var, WT_GOOGLE_API_KEY but provides pointers to get it :-)

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