我正在尝试通过在各种论坛中找到的实现将SYSTEMTIME
转换为time_t
。
time_t TimeFromSystemTime(const SYSTEMTIME * pTime)
{
struct tm tm;
memset(&tm, 0, sizeof(tm));
tm.tm_year = pTime->wYear - 1900; // EDIT 2 : 1900's Offset as per comment
tm.tm_mon = pTime->wMonth - 1;
tm.tm_mday = pTime->wDay;
tm.tm_hour = pTime->wHour;
tm.tm_min = pTime->wMinute;
tm.tm_sec = pTime->wSecond;
tm.tm_isdst = -1; // Edit 2: Added as per comment
return mktime(&tm);
}
但令我惊讶的是,tm
携带的数据对应于当地时间,但mktime()
返回的time_t
对应于UTC时间。
是这样工作的,还是我遗漏了什么?
感谢您的提前帮助!!
编辑1:我想将携带我的本地时间的SYSTEMTIME
准确地转换为time_t
。
我在基于VC6的MFC应用程序中使用这个。
第2版:修改后的代码。
我终于从Windows SDK中找到了解决方案,通过TIME_ZONE_INFORMATION和_timezone
time_t GetLocaleDateTime( time_t ttdateTime) // The time_t from the mktime() is fed here as the Parameter
{
if(ttdateTime <= 0)
return 0;
TIME_ZONE_INFORMATION tzi;
GetTimeZoneInformation(&tzi); // We can also use the StandardBias of the TIME_ZONE_INFORMATION
int iTz = -_timezone; // Current Timezone Offset from UTC in Seconds
iTz = (iTz > 12*3600) ? (iTz - 24*3600) : iTz; // 14 ==> -10
iTz = (iTz < -11*3600) ? (iTz + 24*3600) : iTz; // -14 ==> 10
ttdateTime += iTz;
return ttdateTime;
}
编辑1:请添加您的评论,如果您看到任何错误,请随时评论或编辑。谢谢