Skip to content

Instantly share code, notes, and snippets.

@brianm

brianm/wt

Last active Sep 13, 2018
Embed
What would you like to do?
#! /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

This comment has been minimized.

Copy link
Owner Author

@brianm 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
You can’t perform that action at this time.