我正在尝试通过在各种论坛中找到的实现将 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:修改代码。
最佳答案
我终于通过 TIME_ZONE_INFORMATION 从 Windows SDK 找到了解决方案和 _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: 请添加您的评论,如果您发现任何错误,请随时评论或编辑。谢谢。
关于c++ - 从 SYSTEMTIME 到 time_t 的转换给出 UTC/GMT 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28696211/