How to Find the Current System Timezone

How do I find the current system timezone?

It's hard to get a reliable answer. Relying on things like /etc/timezone may be the best bet.

(The variable tzname and the tm_zone member of struct tm, as suggested in other answers, typically contains an abbreviation such as GMT/BST etc, rather than the Olson time string as requested in the question).

  • On Debian-based systems (including Ubuntu), /etc/timezone is a file containing the right answer.
  • On some Redhat-based systems (including at least some versions of CentOS, RHEL, Fedora), you can get the required information using readlink() on /etc/localtime, which is a symlink to (for example) /usr/share/zoneinfo/Europe/London.
  • OpenBSD seems to use the same scheme as RedHat.

However, there are some issues with the above approaches. The /usr/share/zoneinfo directory also contains files such as GMT and GB, so it's possible the user may configure the symlink to point there.

Also there's nothing to stop the user copying the right timezone file there instead of creating a symlink.

One possibility to get round this (which seems to work on Debian, RedHat and OpenBSD) is to compare the contents of the /etc/localtime file to the files under /usr/share/zoneinfo, and see which ones match:

eta:~% md5sum /etc/localtime
410c65079e6d14f4eedf50c19bd073f8 /etc/localtime
eta:~% find /usr/share/zoneinfo -type f | xargs md5sum | grep 410c65079e6d14f4eedf50c19bd073f8
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/London
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Belfast
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Guernsey
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Jersey
410c65079e6d14f4eedf50c19bd073f8 /usr/share/zoneinfo/Europe/Isle_of_Man
...
...

Of course the disadvantage is that this will tell you all timezones that are identical to the current one. (That means identical in the full sense - not just "currently at the same time", but also "always change their clocks on the same day as far as the system knows".)

Your best bet may be to combine the above methods: use /etc/timezone if it exists; otherwise try parsing /etc/localtime as a symlink; if that fails, search for matching timezone definition files; if that fails - give up and go home ;-)

(And I have no idea whether any of the above applies on AIX...)

Get date in current timezone in Java

Here is a way to get the id of a TimeZone that matches your local system clock's offset,

Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
// Got local offset, now loop through available timezone id(s).
String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (tz.getRawOffset() == milliDiff) {
// Found a match.
name = id;
break;
}
}
System.out.println(name);

How to get the current date and time of your timezone in Java?

Date is always UTC-based... or time-zone neutral, depending on how you want to view it. A Date only represents a point in time; it is independent of time zone, just a number of milliseconds since the Unix epoch. There's no notion of a "local instance of Date." Use Date in conjunction with Calendar and/or TimeZone.getDefault() to use a "local" time zone. Use TimeZone.getTimeZone("Europe/Madrid") to get the Madrid time zone.

... or use Joda Time, which tends to make the whole thing clearer, IMO. In Joda Time you'd use a DateTime value, which is an instant in time in a particular calendar system and time zone.

In Java 8 you'd use java.time.ZonedDateTime, which is the Java 8 equivalent of Joda Time's DateTime.

How do I get the current time zone of MySQL?

From the manual (section 9.6):

The current values of the global and client-specific time zones can be retrieved like this:

mysql> SELECT @@global.time_zone, @@session.time_zone;

Edit The above returns SYSTEM if MySQL is set to use the system's timezone, which is less than helpful. Since you're using PHP, if the answer from MySQL is SYSTEM, you can then ask the system what timezone it's using via date_default_timezone_get. (Of course, as VolkerK pointed out, PHP may be running on a different server, but as assumptions go, assuming the web server and the DB server it's talking to are set to [if not actually in] the same timezone isn't a huge leap.) But beware that (as with MySQL), you can set the timezone that PHP uses (date_default_timezone_set), which means it may report a different value than the OS is using. If you're in control of the PHP code, you should know whether you're doing that and be okay.

But the whole question of what timezone the MySQL server is using may be a tangent, because asking the server what timezone it's in tells you absolutely nothing about the data in the database. Read on for details:

Further discussion:

If you're in control of the server, of course you can ensure that the timezone is a known quantity. If you're not in control of the server, you can set the timezone used by your connection like this:

set time_zone = '+00:00';

That sets the timezone to GMT, so that any further operations (like now()) will use GMT.

Note, though, that time and date values are not stored with timezone information in MySQL:

mysql> create table foo (tstamp datetime) Engine=MyISAM;
Query OK, 0 rows affected (0.06 sec)

mysql> insert into foo (tstamp) values (now());
Query OK, 1 row affected (0.00 sec)

mysql> set time_zone = '+01:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select tstamp from foo;
+---------------------+
| tstamp |
+---------------------+
| 2010-05-29 08:31:59 |
+---------------------+
1 row in set (0.00 sec)

mysql> set time_zone = '+02:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select tstamp from foo;
+---------------------+
| tstamp |
+---------------------+
| 2010-05-29 08:31:59 | <== Note, no change!
+---------------------+
1 row in set (0.00 sec)

mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2010-05-29 10:32:32 |
+---------------------+
1 row in set (0.00 sec)

mysql> set time_zone = '+00:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2010-05-29 08:32:38 | <== Note, it changed!
+---------------------+
1 row in set (0.00 sec)

So knowing the timezone of the server is only important in terms of functions that get the time right now, such as now(), unix_timestamp(), etc.; it doesn't tell you anything about what timezone the dates in the database data are using. You might choose to assume they were written using the server's timezone, but that assumption may well be flawed. To know the timezone of any dates or times stored in the data, you have to ensure that they're stored with timezone information or (as I do) ensure they're always in GMT.

Why is assuming the data was written using the server's timezone flawed? Well, for one thing, the data may have been written using a connection that set a different timezone. The database may have been moved from one server to another, where the servers were in different timezones (I ran into that when I inherited a database that had moved from Texas to California). But even if the data is written on the server, with its current time zone, it's still ambiguous. Last year, in the United States, Daylight Savings Time was turned off at 2:00 a.m. on November 1st. Suppose my server is in California using the Pacific timezone and I have the value 2009-11-01 01:30:00 in the database. When was it? Was that 1:30 a.m. November 1st PDT, or 1:30 a.m. November 1st PST (an hour later)? You have absolutely no way of knowing. Moral: Always store dates/times in GMT (which doesn't do DST) and convert to the desired timezone as/when necessary.

How to find current system timezone

time.h defines a function to retrieve the system timezone and save it in two string variables:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main() {
char * TZ = getenv("TZ");
if (TZ)
printf("TZ: %s\n", TZ);
tzset();
printf("Timezone: %s/%s\n", tzname[0], tzname[1]);
printf("GMT %s%ld\n", timezone >= 0 ? "+" : "", timezone);
printf("DST %s\n", daylight ? "ON" : "OFF");
}

Please note that on some systems (e.g. Linux) this function retrieves it's information from the TZ environment variable. If it is not set then an approximation will be given or the variables will remain uninitialised.

On my OS X this info seems to come from somewhere else.

Get time zone information of the system in Python?

Check out the Python Time Module.

from time import gmtime, strftime
print(strftime("%z", gmtime()))

Pacific Standard Time

Find if system timezone is ahead or behind UTC in java

You can compare the no. of seconds by which a zone is offset e.g.

import java.time.Instant;
import java.time.ZoneOffset;

public class Main {
public static void main(String[] args) {
long offsetSecondsMyTZ = ZoneOffset.systemDefault().getRules().getOffset(Instant.now()).getTotalSeconds();
if (offsetSecondsMyTZ > 0) {
System.out.println("My timezone is ahead of UTC");
} else if (offsetSecondsMyTZ < 0) {
System.out.println("My timezone is behind UTC");
} else {
System.out.println("My timezone is UTC");
}

// Assuming my time-zone is UTC
offsetSecondsMyTZ = ZoneOffset.UTC.getTotalSeconds();
if (offsetSecondsMyTZ > 0) {
System.out.println("My timezone is ahead of UTC");
} else if (offsetSecondsMyTZ < 0) {
System.out.println("My timezone is behind UTC");
} else {
System.out.println("My timezone is UTC");
}

// Assuming my time-zone is UTC - 2 hours
offsetSecondsMyTZ = ZoneOffset.ofHours(-2).getTotalSeconds();
if (offsetSecondsMyTZ > 0) {
System.out.println("My timezone is ahead of UTC");
} else if (offsetSecondsMyTZ < 0) {
System.out.println("My timezone is behind UTC");
} else {
System.out.println("My timezone is UTC");
}
}
}

Output:

My timezone is ahead of UTC
My timezone is UTC
My timezone is behind UTC

Note: This solution is based on this answer.

How to get the local timezone from the system using nodejs

The existing answers will tell you the current timezone offset, but you will have issues if you are comparing historic/future points in time as this will not cater for daylight saving changes.

In many timezones, the offset varies throughout the year and these changes occur at different dates or not at all depending on the latitude. If you only have UTC time and an offset, you can never be sure what the offset will be in that location at various other times during the year.

For example, a UTC+2:00 offset could refer to Barcelona in the summer or Ivory Coast all year round. The 2hr offset will always display the correct time in Ivory Coast but will be 1hr out for half the year in Barcelona.

Check out this great article covering the above.

How do we cater for all these time zone issues? Well, it's pretty simple:

  1. Save all times in UTC
  2. Store the time zone string for where this event occurred

In modern browsers or node.js, you can get the local IANA time zone string like this:

Intl.DateTimeFormat().resolvedOptions().timeZone // eg. 'America/Chicago'

You can then use this timezone string in a library like Luxon to help offset your captured UTC times.

DateTime.fromISO("2017-05-15T09:10:23", { zone: "Europe/Paris" });


Related Topics



Leave a reply



Submit