Converting string containing localtime into UTC in C

前端 未结 3 1884
长发绾君心
长发绾君心 2021-01-13 09:12

I have a string containing a local date/time and I need to convert it to a time_t value (in UTC) - I\'ve been trying this:

char* date = \"2009/09/01/00\";
st         


        
3条回答
  •  清酒与你
    2021-01-13 09:49

    I think I've cracked it now, thanks to Andomar - this code does what I need and appears to work regardless of the current DST status (I changed the clock on my PC to check this):

    #include 
    #include 
    
    time_t parseLocalDate(char* date){
        struct tm cal = {0, 0, 0, 0, 0, 0, 0, 0, -1, 0, NULL};
        strptime(date, "%Y/%m/%d/%H", &cal);
        return mktime(&cal);
    }
    
    int main(int argc, char *argv[]){
     // DST is effect, Local Time = GMT+1
        assert(1251759600 == parseLocalDate("2009/09/01/00")); // Mon, 31 Aug 2009 23:00:00 GMT
        assert(1254351600 == parseLocalDate("2009/10/01/00")); // Wed, 30 Sep 2009 23:00:00 GMT
     // DST not in effect, Local Time = GMT
        assert(1257033600 == parseLocalDate("2009/11/01/00")); // Sun, 01 Nov 2009 00:00:00 GMT
    }
    

提交回复
热议问题