我需要将格式为“2011061411322100”的一些字符串时间转换为 GMT - 我的第一次尝试如下。但问题是,时间来自另一台电脑,而且是历史时间。所以我没有实时获取时间,所以我不能简单地从我的代码运行的盒子上的当地时间获取 GMT。
问题是,如果我的代码在时间更改期间运行,则时间更改将发生在我的盒子上,但不会发生在我获取时间的远程盒子上。但是,我可以随时查询该框以获取当前时间。
因此,提供更多详细信息:
- 我在远程盒子上开始工作
- 作业完成
- 我得到一些与正在运行的作业相关的时间
- 我将时间转换为 GMT
如果 1. 和 2. 之间发生时间变化(夏令时),我就完蛋了。我的 GMT 转换将会中断。我想在 2) 之后我需要获取当前的远程盒时间并查看是否存在 >58 分钟的差异,然后将其应用于转换。但我无法找出可靠的方法来做到这一点。
string GMTConverter::strToGMT(const string& timeToConvert)
{
// Set time zone from TZ environment variable.
_tzset();
struct tm tmTime;
//2011 06 14 11 32 21 00
// (strToInt is just a wrapper for atoi)
int year = strToint(timeToConvert.substr(0, 4) );
int month = strToint(timeToConvert.substr(4, 2) );
int day = strToint(timeToConvert.substr(6, 2) );
int hour = strToint(timeToConvert.substr(8, 2) );
int min = strToint(timeToConvert.substr(10, 2) );
int sec = strToint(timeToConvert.substr(12, 2) );
cout<<"Time after parsing: "<<year<<"/"<<month<<"/"<<day<<" "<<hour<<":"<<min<<":"<<sec<<endl;
// add to tm struct and return
tmTime.tm_hour = hour;
tmTime.tm_min = min;
tmTime.tm_sec = sec;
tmTime.tm_mday = day;
tmTime.tm_mon = (month-1);
tmTime.tm_year = (year - 1900);
cout <<"Time in TM: "<<tmTime.tm_year<<"/"<<tmTime.tm_mon<<"/"<<tmTime.tm_mday<<" "<<tmTime.tm_hour<<":"<<tmTime.tm_min<<":"<<tmTime.tm_sec<<endl;
char currDateTime[64];
// For logging
strftime(currDateTime, 63, "%c", &tmTime);
cout <<"Actual time:"<<currDateTime<<endl;
time_t remotePCTime = mktime( &tmTime );
struct tm *gmt = gmtime( &remotePCTime );
cout << "gmt = " << asctime( gmt ) << endl;
char datebuf_2[12];
char timebuf_2[13];
strftime( datebuf_2, 13, "%Y-%m-%d\0", gmt );
strftime( timebuf_2, 13, "%H:%M:%S\0", gmt );
return string(datebuf_2) + "T" + string(timebuf_2) + "." + string("000");
}