Getting Abbreviated timezone using strftime() using C

可紊 提交于 2019-12-23 15:12:59

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/39237889/getting-abbreviated-timezone-using-strftime-using-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!