8

Unfortunately timedatectl set-timezone doesn't update /etc/timezone.

How do I get the current timezone as Region/City, eg, given:

% timedatectl | grep zone
                       Time zone: Asia/Kuala_Lumpur (+08, +0800)

I can get the last part:

% date +"%Z %z"
+08 +0800

How do I get theAsia/Kuala_Lumpur part without getting all awk-ward?

I'm on Linux, but is there also a POSIX way?

Tom Hale
  • 28,728
  • 32
  • 139
  • 229
  • 1
    Don't you have /etc/localtime as symbolic link to zoneinfo file? ( e.g. /etc/localtime -> ../usr/share/zoneinfo/Europe/Madrid ) In such case, you could get is by readlink /etc/localtime | sed "s[.*zoneinfo/[[" – tonioc Jun 25 '18 at 10:52

2 Answers2

6

In this comment by Stéphane Chazelas, he said:

timedatectl is a systemd thing that queries timedated over dbus and timedated derives the name of the timezone (like Europe/London) by doing a readlink() on /etc/localtime. If /etc/localtime is not a symlink, then that name cannot be derived as those timezone definition files don't contain that information.

Based on this and tonioc's comment, I put together the following:

#!/bin/bash
set -euo pipefail

if filename=$(readlink /etc/localtime); then
    # /etc/localtime is a symlink as expected
    timezone=${filename#*zoneinfo/}
    if [[ $timezone = "$filename" || ! $timezone =~ ^[^/]+/[^/]+$ ]]; then
        # not pointing to expected location or not Region/City
        >&2 echo "$filename points to an unexpected location"
        exit 1
    fi
    echo "$timezone"
else  # compare files by contents
    # https://stackoverflow.com/questions/12521114/getting-the-canonical-time-zone-name-in-shell-script#comment88637393_12523283
    find /usr/share/zoneinfo -type f ! -regex ".*/Etc/.*" -exec \
        cmp -s {} /etc/localtime \; -print | sed -e 's@.*/zoneinfo/@@' | head -n1
fi
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
Tom Hale
  • 28,728
  • 32
  • 139
  • 229
  • 1
    [You have a good eye](https://unix.stackexchange.com/revisions/451925/2), thanks for the update, @StephenKitt. – Tom Hale Jun 26 '18 at 07:01
5

For the time zone, you can use geolocation:

$ curl https://ipapi.co/timezone
America/Chicago

Or:

$ curl http://ip-api.com/line?fields=timezone
America/Chicago

http://wiki.archlinux.org/index.php/time#Time_zone

Zombo
  • 1
  • 5
  • 43
  • 62