返回的C ++时间是两个小时

时间:2012-10-23 11:56:37

标签: c++ ctime

有点c ++新手,所以我们走了;

我有一个解析日期/时间的方法,但是该日期/时间总是以00:00:00传递给我,如hh:mm:ss。因此,我想添加当前systime的值来代替这些值。我有方法执行此操作,第一种方法是以UTC格式返回正确的时间。

bool CTRHTranslationRTNS::ParseDateSysTime(const char* pszString, time_t& tValue)
{
    ASSERT(pszString != NULL);

    // DateTime fields.
    enum { YEAR, MONTH, DAY, HOURS, MINS, SECS, NUM_FIELDS };

    CStringArray astrFields;

    // Split the string into the date and time fields.
    int nFields = CStringParser::Split(pszString, "- :T", astrFields);

    // Not DD/MM/YYYY HH:MM:SS format.
    if (nFields != NUM_FIELDS)
        return false;

    int anFields[NUM_FIELDS] = { 0 };

    // Parse field numbers.
    for (int i = 0; i < NUM_FIELDS; ++i)
        anFields[i] = atoi(astrFields[i]);

    tm oTime = { 0 };

        //Add System Time instead
        time_t sysyemTimeNow;
        struct tm * ptm;
        time ( &sysyemTimeNow );
        ptm = gmtime ( &sysyemTimeNow );

    // Copy fields to time struct.
    oTime.tm_mday  = anFields[DAY];
    oTime.tm_mon   = anFields[MONTH] - 1;
    oTime.tm_year  = anFields[YEAR] - 1900;
    oTime.tm_hour  = ptm->tm_hour;
    oTime.tm_min   = ptm->tm_min;
    oTime.tm_sec   = ptm->tm_sec;
    oTime.tm_isdst = -1;

    // Convert to time_t.
    tValue = mktime(&oTime);

    // Invalid field values.
    if (tValue < 0)
        return false;

    return true;
}

在第二种方法中,我对日期/时间进行了一些格式化,这导致从时间上移除2小时。

string CTRHTranslationRTNS::ConvertDateSysTimeToDateInUTC(const string& bossDate)
{
    time_t dealDate;
    if (ParseDateSysTime(bossDate.c_str(), dealDate))
    {
        struct tm * ptm = gmtime(&dealDate);
        char buffer [80];
        strftime(buffer,80,"%Y-%m-%d %H:%M:%S",ptm);
        return string(buffer);
    }
    else
    {
        throw exception(string("Invalid date/SysTime value: ").append(bossDate).c_str());   
    }   
}

为了清楚起见,ParseDateSysTime方法返回正确的UTC值为11:53的时间,但是只要

struct tm * ptm = gmtime(&dealDate);

被称为时间变为08:53。它表明这是调用gmtime()方法的产物,但我不确定。

非常感谢

格雷厄姆

2 个答案:

答案 0 :(得分:4)

原因是第一个函数中使用的mktime()方法使用本地时间,但gmtime()使用 UTC时间

有关详细说明,请参阅http://www.cplusplus.com/reference/clibrary/ctime/mktime/http://www.cplusplus.com/reference/clibrary/ctime/gmtime/

答案 1 :(得分:2)

尝试此功能:

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;
}