Reputation: 11920
In my app, I convert user-specified time into time_t
format and store it. At a later point, I display this time in local time zone. Here is my test code:
int main() {
const char* INPUTFMT = "%b %d, %Y %H:%M:%S %Z";
const char* SAMPLETIME = "Feb 19, 2016 01:00:00 EST";
struct tm tm = {0};
char* val = strptime(SAMPLETIME, INPUTFMT, &tm);
time_t st = mktime(&tm);
const struct tm* t1 = localtime(&st);
static const char* OUTPUTFMT = "%b %d, %G %I:%M:%S %p %Z";
char buf[100];
strftime (buf, 100, OUTPUTFMT, t1);
printf("%s\n", buf);
return 0;
}
The specified timezone is EST and my local timezone is PST.
The problem I am running into is that, although my local timezone is different than the one specified, I see the same time except that EST is replaced by PST.
I am wondering what is it that I am doing wrong. Regards.
Upvotes: 3
Views: 430
Reputation: 219568
The man-page for strptime
on my system (OS X) says:
The %Z format specifier only accepts time zone abbreviations of the local time zone, or the value "GMT". This limitation is because of ambiguity due to of the over loading of time zone abbreviations. One such example is EST which is both Eastern Standard Time and Eastern Australia Summer Time.
Thus this line:
char* val = strptime(SAMPLETIME, INPUTFMT, &tm);
is silently ignoring the "EST" in the input and instead using your current local time offset instead. And thus when you convert it back from your current local time here:
strftime (buf, 100, OUTPUTFMT, t1);
You get a round-trip from your current local time to UTC and back to your current local time.
See this language-neutral stack overflow answer for more advice on how to handle timezones.
Upvotes: 3