题
继续 我尝试创建DateTime课程 ,我正在尝试将“时代”时间存储在我的功能中:
void DateTime::processComponents(int month, int day, int year,
int hour, int minute, int second) {
struct tm time;
time.tm_hour = hour;
time.tm_min = minute;
time.tm_sec = second;
time.tm_mday = day;
time.tm_mon = month;
time.tm_year = year - 1900;
ticks_ = mktime(&time);
processTm(time);
}
void DateTime::processTm(struct tm time) {
second_ = time.tm_sec;
minute_ = time.tm_min;
hour_ = time.tm_hour;
weekday_ = time.tm_wday;
monthday_ = time.tm_mday;
yearday_ = time.tm_yday;
month_ = time.tm_mon;
year_ = time.tm_year + 1900;
}
在任意日期, processComponents(5,5,1990,1,23,45)
(1990年6月6日,上午1:23:45),它可以正确地设置所有值。
但是,经过进一步的测试,我发现 processComponents(0,0,1970,0,0,0)
(1970年1月1日,上午12:00:00), mktime(&time)
原因 time
被搞砸了:
time.tm_mon = 11;
time.tm_mday = 30;
time.tm_year = 69;
time.tm_hour = 23;
time.tm_min = 0;
time.tm_sec = 0;
time.tm_isdst = 0;
time.tm_gmtoff = -18000;
time.tm_zone = "EST";
time.tm_wday = 2;
time.tm_yday = 363;
转化为1969年12月31日的日期11:00:00 pm。
我可以验证 mktime()
负责,因为通过发表评论,它正确地报告了日期和时间为1970年1月1日12:00:00 am。
为什么是 mktime()
只弄乱了这个时代?我应该如何解决 /解决这个问题?
谢谢!
解决方案
您通过0作为 day
参数并将其放入 time.tm_mday
. 。该组件(以及仅此组件)的 struct tm
是基于1的,而不是基于0的。
不要问我为什么。
要指定1970年1月1日,上午12:00:00您想这样称呼:
processComponents(0,1,1970,0,0,0);
并作为 SDTOM提到, ,您要确保 tm_isdst
适当设置-0对于无效,对有效的阳性,对您不知道的负面(在这种情况下 mktime()
应该尝试猜测)。
只是为了让您知道,当我通过日期时(1970年1月0日,00:00:00) mktime()
在MSVC 9中,它返回错误(通过 struct tm
未被触及,返回 time_t
值是-1)。
其他提示
由于它已经停止了一小时,所以我预计夏令时会储蓄时间。 tim.tm_isdst是否设置在某个地方?如果您不设置它,则可以随机设置为1或0,这会影响您的结果。
将所有零传递给 mktime()
被解释为“ 1900年1月00:00:00”。基于此,需要进行一些调整...
// the input is local time
// the output is seconds since the epoch
// The epoch is Jan 1, 1970 @ 0:00 GMT
time_t mktime_wrapper( int month, int day, int year,
int hour=0, int min=0, int sec=0, bool isDST=-1
)
{
tm t;
t.tm_sec=sec, t.tm_min=min, t.tm_hour=hour, t.tm_isdst=isDST;
t.tm_mday=day, t.tm_mon=month-1, t.tm_year=year-1900;
return mktime( &t );
}