C++ Converting a time string to seconds from the epoch

前端 未结 10 583
無奈伤痛
無奈伤痛 2020-12-01 14:53

I have a string with the following format:

2010-11-04T23:23:01Z

The Z indicates that the time is UTC.
I would rather store t

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 15:10

    X/Open provides a global timezone variable which indicates the number of seconds that local time is behind UTC. You can use this to adjust the output of mktime():

    #define _XOPEN_SOURCE
    #include 
    #include 
    
    /* 2010-11-04T23:23:01Z */
    time_t zulu_time(const char *time_str)
    {
        struct tm tm = { 0 };
    
        if (!strptime(time_str, "%Y-%m-%dT%H:%M:%SZ", &tm))
            return (time_t)-1;
    
        return mktime(&tm) - timezone;
    }
    

提交回复
热议问题