gpt4 book ai didi

返回的 C++ 时间晚了两个小时

转载 作者:搜寻专家 更新时间:2023-10-31 00:17:36 25 4
gpt4 key购买 nike

有点像 C++ 新手,所以我们开始吧;

我有一个解析日期/时间的方法,但是该日期/时间总是以 00:00:00 作为 hh:mm:ss 传递给我。因此,我想添加当前系统时间的值来代替这些值。我有执行此操作的方法,第一种方法是以 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() 方法的产物,但我不确定。

非常感谢

格雷厄姆

最佳答案

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

参见 http://www.cplusplus.com/reference/clibrary/ctime/mktime/http://www.cplusplus.com/reference/clibrary/ctime/gmtime/进一步解释。

关于返回的 C++ 时间晚了两个小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13029894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com