假设我得到了这样一个字符串:"2009-4-9"
,表示 2009 年 4 月 9 日。假设对于初学者来说,我只关心本地时间(我也担心其他时区,但我会先解决简单的问题)。了解夏令时当时是否有效的最佳方法是什么?
您可以假设系统具有正确更新的时区文件,例如 /etc/localtime
并且我对可移植的解决方案很感兴趣。 c 或 c++ 也可以接受。
你也可以假设我只关心过去或现在的日期,从不关心 future 。
目前我有一个看起来像这样的“hack”(我知道 localtime_r 是一个库扩展,但它与我可以使其可移植的相同功能足够接近)
struct tm tm;
// convert the time string to a broken down structure in localtime
if(strptime("2009-4-9", "%Y-%m-%d", &tm)) {
// convert the broken down structure into seconds since epoch
const time_t t = mktime(&tm);
// convert it back to a broken down structure, this seems pointless at first...
// but libc will fill out fields such as tm_isdst
localtime_r(&t, &tm);
printf("DST : %d\n", tm.tm_isdst);
}
虽然这很有效(而且似乎是一种非常有效的方法),但我觉得来回转换很愚蠢。有没有更好的办法?
最佳答案
您根本不需要调用 localtime_r()
。 mktime()
标准化您传递给它的 struct tm
,包括将 tm_isdst
设置为非负值(如果它被设置为 ) -1
。所以你只需要:
struct tm tm = { 0 };
// convert the time string to a broken down structure in localtime
if(strptime("2009-4-9", "%Y-%m-%d", &tm)) {
tm.tm_isdst = -1;
// normalise the broken down structure - this calculates tm_isdst
mktime(&tm);
printf("DST : %d\n", tm.tm_isdst);
}
mktime()
的这种行为是 C 标准所要求的;例如,C99 说:
The
mktime
function converts the broken-down time, expressed as local time, in the structure pointed to bytimeptr
into a calendar time value with the same encoding as that of the values returned by thetime
function. The original values of thetm_wday
andtm_yday
components of the structure are ignored, and the original values of the other components are not restricted to the ranges indicated above.276 On successful completion, the values of thetm_wday
andtm_yday
components of the structure are set appropriately, and the other components are set to represent the specified calendar time, but with their values forced to the ranges indicated above; the final value oftm_mday
is not set untiltm_mon
andtm_year
are determined.
脚注 276 明确解决了 tm_isdst
成员:
276) Thus, a positive or zero value for
tm_isdst
causes themktime
function to presume initially that Daylight Saving Time, respectively, is or is not in effect for the specified time. A negative value causes it to attempt to determine whether Daylight Saving Time is in effect for the specified time.
关于c++ - 给定一个字符串形式的日期/时间,知道当时是否为 DST 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9403015/