ryyker ryyker - 8 months ago 38
C Question

Getting Abbreviated timezone using strftime() using C

I have viewed this, and this, on SO, but they deal with non-C variations of the same problem.

Using GNU GCC compiler (Code::Blocks, in Windows) with the following code:

int main(void)
time_t rawtime;
struct tm *info;
char timeStr[80];

time( &rawtime );
info = localtime( &rawtime );

strftime(timeStr,80,"%a %b %d %H:%M:%S %Z %Y", info);

printf("%s", timeStr);

return 0;

I am getting the this time string:

Tue Aug 30 14:55:08 Pacific Daylight Time 2016

Everything is fine except time zone. I prefer it to be abbreviated, such as:

Tue Aug 30 14:55:08 PDT 2016

In every man page, or windows documentation for strftime() I can find the description for the format specifier %Z goes something like: Timezone name or abbreviation. ( eg. here. )

What is the trick to formatting timezone to be abbreviated?


strftime gives no guarantee whether you'll get the full name or the abbreviation. It is implementation dependent. The C99 spec (and Microsoft's documentation) says:

%Z is replaced by the locale’s time zone name or abbreviation, or by no characters if no time zone is determinable.

AFAIK there is no standard C way to guarantee you'll get the time zone abbreviation. That assumes you use the system time zone database. You could ship with your own copy of the time zone database.

In general, time zone abbreviations are a bad idea because they're ambiguous. Skimming the list we find ACT, AMT, BST, ECT, GST, IST, LHST, MST, PST, and SST are all ambiguous. You're better off using the full name, the numeric offset (ie. %z), or eschew time zones altogether and use UTC (particularly useful for logging).