c ++ strptime解析时忽略时区

问题描述 投票:1回答:2

当我运行以下代码时,strptime似乎忽略了时区值。只需设置本地时区的值(即+10)。

这是输出,((在Linux上运行,使用gcc 4.6.3编译):

-----------2013-04-24T9:47:06+400 - %Y-%m-%dT%H:%M:%S%z
TM Break    H:9 is DST:0 GMT Off:0
The epoch value:    1366760826
DateTime in String:     04/24/13 - 09:47AM +1000

-----------2013-04-24T11:47:06+800 - %Y-%m-%dT%H:%M:%S%z
TM Break    H:11 is DST:0 GMT Off:36000
The epoch value:    1366768026
DateTime in String:     04/24/13 - 11:47AM +1000

-----------2013-04-24T9:47:06+0 - %Y-%m-%dT%H:%M:%S%z
TM Break    H:9 is DST:0 GMT Off:36000
The epoch value:    1366760826
DateTime in String:     04/24/13 - 09:47AM +1000

-----------2013-04-24T9:47:06+4 - %Y-%m-%dT%H:%M:%S%z
TM Break    H:9 is DST:0 GMT Off:36000
The epoch value:    1366760826
DateTime in String:     04/24/13 - 09:47AM +1000

这是代码:

void date_Test(){
    string dateStrings[] = {"2013-04-24T9:47:06+400"
                          , "2013-04-24T11:47:06+800"
                          , "2013-04-24T9:47:06+0"
                          , "2013-04-24T9:47:06+4"};
    string formatStrings[] = {"%Y-%m-%dT%H:%M:%S%z"
                            , "%Y-%m-%dT%H:%M:%S%z"
                            , "%Y-%m-%dT%H:%M:%S%z"
                            , "%Y-%m-%dT%H:%M:%S%z"};

process_Timezone(dateStrings, formatStrings);
}

void process_Timezone(string dateStrings[], string formatStrings[]){
    int num = 4; 

    for (int i = 0; i < num; i++) {
        cout << endl << "-----------" << dateStrings[i] << " - " << formatStrings[i] << endl;
        tm *dtm = new tm;
        strptime(dateStrings[i].c_str(), formatStrings[i].c_str(), dtm);
        cout << "TM Break \tH:" << dtm->tm_hour << " is DST:" << dtm->tm_isdst << " GMT Off:"  << dtm->tm_gmtoff << endl;
        time_t ep_dt = mktime(dtm);
        cout << "The epoch value: \t" << ep_dt << endl;
        char buffer[40];
        strftime(buffer, 40,"%x - %I:%M%p %z", dtm);
        cout << "DateTime in String: \t" << buffer << endl;
        delete dtm;
    }
}
c++ parsing time timezone strptime
2个回答
2
投票

根据http://en.wikipedia.org/wiki/ISO_8601,您的一位数和三位数的时区偏移量不是有效的ISO 8601值(至少在Linux上为strptime使用的格式),因此需要hh[:][mm]作为格式。


0
投票

可能晚了,但是strptime确实正确解析了%z说明符,并将其存储在tm.tm_gmtoff变量中。此变量不是标准变量,而是gnu扩展名。 mktime不使用此变量。

您可以尝试

strptime(<time_string>, dtm);
std::cout << dtm->tm_gmtoff;

以查看解析的时间偏移。

注意.tm_gmtoff以秒为单位,所以可以获取正确的纪元时间

auto offset = dtm->tm_gmtoff;
auto _epoch = mktime(dtm);
auto final_epoch = _epoch + offset

来源

© www.soinside.com 2019 - 2024. All rights reserved.