返回的C 时间为两个小时

C++ Time returned is two hours out

本文关键字:两个 小时 时间 返回      更新时间:2023-10-16

c newbie的位,所以我们去;

我有一种正在解析日期/时间的方法,但是该日期/时间总是以00:00:00为HH:MM:SS的00:00:00传递给我。因此,我想添加当前的临时值代替这些值。我有这样做的方法,第一个方法是以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());   
    }   
}

要清楚,放置的stimestime方法以11:53的正确UTC值返回时间,但是只要

struct tm * ptm = gmtime(&dealDate);

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

非常感谢

格雷厄姆

第一个函数中使用的mktime()方法 local Time ,但是gmtime()使用 utc time

请参阅http://www.cplusplus.com/reference/clibrary/ctime/mktime/and http://www.cplusplus.com/reference/reference/clibrary/clibrary/ctime/gmmite/进一步说明。

<</p> /div>

尝试此功能:

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