我有一个系统,我以字符串的形式提供日期和时间,例如"2011-03-13 03:05:00".我可能会在"2011-03-13 01:59:00"收到此字符串,我需要知道从现在到字符串中的时间之间的时间长度(由于DST更改,时间为6分钟).
我有代码解析字符串并创建一个tm结构,然后转换为time_twith mktime.问题是我必须tm_isdst在解析时间时手动设置标志,所以我正在寻找一种方法来检测是否tm_isdst应该设置.有任何想法吗?
我对如何处理那里有2个的情况下,2AMs这将是具体到我的应用程序的一些想法,但我仍然需要一种方式说"如果这个时间是当前系统时间,将DST生效?"
编辑:基于Pete建议的想法.如果我:
思考?
根据man mktime(在Linux上,强调我的):
tm_isdst字段中指定的值通知mktime()夏令时(DST)是否对tm结构中提供的时间有效:正值表示DST有效; 零表示DST无效; 负值表示mktime()应该(使用时区信息和系统数据库)尝试确定DST是否在指定时间生效.
你试过吗?
(这是"试图确定",因为有些时候基本上是模棱两可的.)
对于真正模糊的时代你可以尝试的是看看是否mktime"纠正"了你的dst旗帜.我敢打赌这不是便携式的.示例代码,转换设置于2010年10月31日,凌晨3点在我的时区(欧洲/巴黎)回滚至凌晨2点:
#include <time.h>
#include <stdio.h>
#include <string.h>
void printit(int hour, int isdst)
{
struct tm when;
memset(&when, 0, sizeof(when));
when.tm_sec = 0;
when.tm_min = 30;
when.tm_hour = hour;
when.tm_mday = 31;
when.tm_mon = 9;
when.tm_year = 110;
when.tm_isdst = isdst;
time_t secs = mktime(&when);
fprintf(stdout, "%2d %ld %d %s", isdst, secs, when.tm_isdst, asctime(&when));
}
int main(int argc, char **argv)
{
for (int i=1; i<4; i++) {
fprintf(stdout, "At %dam\n", i);
printit(i, 1);
printit(i, 0);
printit(i, -1);
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
At 1am
1 1288481400 1 Sun Oct 31 01:30:00 2010
0 1288485000 1 Sun Oct 31 02:30:00 2010
-1 1288481400 1 Sun Oct 31 01:30:00 2010
At 2am
1 1288485000 1 Sun Oct 31 02:30:00 2010
0 1288488600 0 Sun Oct 31 02:30:00 2010
-1 1288488600 0 Sun Oct 31 02:30:00 2010
At 3am
1 1288488600 0 Sun Oct 31 02:30:00 2010
0 1288492200 0 Sun Oct 31 03:30:00 2010
-1 1288492200 0 Sun Oct 31 03:30:00 2010
Run Code Online (Sandbox Code Playgroud)
如您所见,当时间不明确时,mktime通过设置右侧tm_isdst和抵消时间来纠正它.当它是不明确的,tm_isdst没有改变.