Skip to content

Commit

Permalink
Update per-platform support for determining the local time zone (goog…
Browse files Browse the repository at this point in the history
…le#101)

Treat the Apple Core Foundation "default time zone" and the
Android "persist.sys.timezone" property consistently as initial
values for the local time zone (overriding ":localtime").  Then
allow ${TZ} to override that on all platforms.

The only slightly confusing thing is CFTimeZoneCopyDefault()
appears to also heed ${TZ} internally, but that's OK.
  • Loading branch information
devbww authored Mar 27, 2019
1 parent 157a94a commit 93f8d10
Showing 1 changed file with 20 additions and 21 deletions.
41 changes: 20 additions & 21 deletions src/time_zone_lookup.cc
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@

#if defined(__APPLE__)
#include <CoreFoundation/CFTimeZone.h>
#include <vector>
#endif

#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>

#include "time_zone_fixed.h"
#include "time_zone_impl.h"
Expand Down Expand Up @@ -120,31 +120,32 @@ time_zone fixed_time_zone(const seconds& offset) {

time_zone local_time_zone() {
const char* zone = ":localtime";

// Allow ${TZ} to override to default zone.
char* tz_env = nullptr;
#if defined(_MSC_VER)
_dupenv_s(&tz_env, nullptr, "TZ");
#elif defined(__APPLE__)
CFTimeZoneRef system_time_zone = CFTimeZoneCopyDefault();
if (CFStringRef tz_name = CFTimeZoneGetName(system_time_zone)) {
#if defined(__ANDROID__)
char sysprop[PROP_VALUE_MAX];
if (__system_property_get("persist.sys.timezone", sysprop) > 0) {
zone = sysprop;
}
#endif
#if defined(__APPLE__)
std::vector<char> buffer;
CFTimeZoneRef tz_default = CFTimeZoneCopyDefault();
if (CFStringRef tz_name = CFTimeZoneGetName(tz_default)) {
CFStringEncoding encoding = kCFStringEncodingUTF8;
CFIndex length = CFStringGetLength(tz_name);
CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, encoding);
std::vector<char> buffer(max_size + 1);
buffer.resize(CFStringGetMaximumSizeForEncoding(length, encoding) + 1);
if (CFStringGetCString(tz_name, &buffer[0], buffer.size(), encoding)) {
tz_env = strdup(&buffer[0]);
zone = &buffer[0];
}
}
CFRelease(system_time_zone);
CFRelease(tz_default);
#endif

// Allow ${TZ} to override to default zone.
char* tz_env = nullptr;
#if defined(_MSC_VER)
_dupenv_s(&tz_env, nullptr, "TZ");
#else
tz_env = std::getenv("TZ");
#endif
#if defined(__ANDROID__)
char sysprop[PROP_VALUE_MAX];
if (tz_env == nullptr)
if (__system_property_get("persist.sys.timezone", sysprop) > 0)
tz_env = sysprop;
#endif
if (tz_env) zone = tz_env;

Expand All @@ -169,8 +170,6 @@ time_zone local_time_zone() {
#if defined(_MSC_VER)
free(localtime_env);
free(tz_env);
#elif defined(__APPLE__)
free(tz_env);
#endif

time_zone tz;
Expand Down

0 comments on commit 93f8d10

Please sign in to comment.