继续使用my attempt to create a DateTime class,我尝试在我的函数中存储“纪元”时间:
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
我可以验证mktime()是否负责,因为通过注释掉该行,它会将日期和时间正确地报告为1970年1月1日12:00:00 am
为什么mktime()只是把时代搞乱了?我应该如何修复/解决这个问题?
谢谢!
发布于 2009-11-08 14:12:16
您将传递0作为day参数并将其放入time.tm_mday中。struct tm的那个组件(并且只有那个组件)是基于1的,而不是基于0的。
别问我为什么。
要将其指定为1970年1月1日12:00:00,您可以这样命名它:
processComponents(0,1,1970,0,0,0);作为sdtom mentioned,您需要确保适当地设置tm_isdst -0表示无效,正值表示有效,负值表示您不知道(在这种情况下,mktime()应该尝试猜测)。
只想让您知道,当我将日期(1970年1月0号00:00:00)传递给MSVC9中的mktime()时,它会返回一个错误(传入的struct tm原封不动,返回的time_t值为-1)。
发布于 2009-11-08 12:52:35
因为差了一个小时,所以我希望是夏令时。time.tm_isdst的值是在什么地方设置的吗?如果您没有设置它,它可能会随机设置为1或0,这将影响您的结果。
发布于 2012-12-21 10:27:17
将全零传递给mktime()被解释为"Sun Jan 0 00:00:00 1900“。在此基础上,需要进行一些调整。
// 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 );
}https://stackoverflow.com/questions/1695389
复制相似问题