Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    getchar();

    return 0;
} 

I am getting 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?

like image 900
ryyker Avatar asked Feb 06 '23 06:02

ryyker


2 Answers

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).

like image 161
Schwern Avatar answered Feb 16 '23 03:02

Schwern


I recently needed the same thing, and determined that there is No Good Answer. I wrote some brute-force code to map Windows timezone strings like "Eastern Standard Time" to "EST", but I knew that (a) this was a Bad Idea and (b) my list of translations would never be complete.

like image 36
Steve Summit Avatar answered Feb 16 '23 02:02

Steve Summit