使用 C 使用 strftime() 获取缩写时区 [英] Getting Abbreviated timezone using strftime() using C

查看:70
本文介绍了使用 C 使用 strftime() 获取缩写时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查看了这个,并且this,关于 SO,但它们处理同一问题的非 C 变体.

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

使用带有以下代码的 GNU GCC 编译器(Code::Blocks,在 Windows 中):

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:

2016 年 8 月 30 日星期二 14:55:08 太平洋夏令时

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

除了时区,一切都很好.我更喜欢缩写,例如:

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

2016 年 8 月 30 日星期二 14:55:08 PDT

Tue Aug 30 14:55:08 PDT 2016

strftime() 的每个手册页或 windows 文档中,我都可以找到格式说明符 %Z 的描述,类似于:时区名称 或缩写.(例如这里.)

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 不保证您会得到全名还是缩写.它依赖于实现.C99 规范(和 Microsoft 的文档)说:

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 替换为区域设置的时区名称或缩写,如果无法确定时区,则不替换任何字符.

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

AFAIK 没有标准的 C 方法来保证您会获得时区缩写.假设您使用系统时区数据库.您可以随附您自己的时区数据库副本.

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.

一般来说,时区缩写是个坏主意,因为它们含糊不清.略读列表,我们发现ACT、AMT、BST、ECT、GST、IST、LHST、MST,PST 和 SST 都是模棱两可的.您最好使用全名、数字偏移量(即 %z),或者完全避开时区并使用 UTC(特别适用于日志记录).

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

这篇关于使用 C 使用 strftime() 获取缩写时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆