4

On previous version of CentOS, I used the following command to get the current timezone in my bash script:

timezone=$(sed 's/ZONE=//g' /etc/sysconfig/clock)

Output is "America/New_York"

How can I achieve an exact output on CentOS 7?

6

CentOS 7 specific:

timedatectl | gawk -F': ' ' $1 ~ /Timezone/ {print $2}'

And displaying just the timezone:

timedatectl | gawk -F'[: ]+' ' $2 ~ /Timezone/ {print $3}'

more generic:

date +%Z
  • Thank you mate...This gives America/New_York (EST, -0500) as ouput.Could you modify your first command to make it display only America/New_York – user2650277 Jan 14 '15 at 16:05
  • @user2650277: With GNU awk: timedatectl | awk '/Timezone:/ {print $2}' – Cyrus Jan 14 '15 at 16:49
1

If you don't mind using perl, you can use DateTime::TimeZone module from CPAN:

$ perl -MDateTime::TimeZone -E '
  say DateTime::TimeZone->new(name => "local")->name();
'
Asia/Ho_Chi_Minh

POSIXly, you can use date with %Z format:

$ date +%Z
ICT
0

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

  • This doesn't seem to jive with the original intent of the question. The locale can be set independent of where the IP of the box resides geo-wise. – slm Jul 1 '18 at 16:46
0
timedatectl | awk '/Time zone:/ {print $3}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.