C++ Time returned is two hours out

泄露秘密 提交于 2019-12-01 22:58:50

The reson is the mktime() method used in the first function uses local time, but gmtime() uses UTC time.

See http://www.cplusplus.com/reference/clibrary/ctime/mktime/ and http://www.cplusplus.com/reference/clibrary/ctime/gmtime/ for further explanation.

Try this function:

CTime Time2UTC(CTime original)
{
    CString Formatted = original.FormatGmt(L"%Y%m%d%H%M%S");
    int Year, Month, Day, Hour, Minute;
    if (Formatted != L"" && Formatted.GetLength() >= 12)
    {
        Year = _wtol(Formatted.Left(4));
        Month = _wtol(Formatted.Mid(4, 2));
        Day = _wtol(Formatted.Mid(6,2));
        Hour = _wtol(Formatted.Mid(8, 2));
        Minute = _wtol(Formatted.Mid(10, 2));
        CTime result(Year, Month, Day, Hour, Minute, 0);
        return result;
    }
    else
        return (CTime)NULL;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!