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

前端 未结 10 605
無奈伤痛
無奈伤痛 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条回答
  •  猫巷女王i
    2020-12-01 15:07

    Problem here is that mktime uses local time not UTC time.

    Linux provides timegm which is what you want (i.e. mktime for UTC time).

    Here is my solution, which I forced to only accept "Zulu" (Z timezone). Note that strptime doesn't actually seem to parse the time zone correctly, even though glib seems to have some support for that. That is why I just throw an exception if the string doesn't end in 'Z'.

    static double EpochTime(const std::string& iso8601Time)
    {
        struct tm t;
        if (iso8601Time.back() != 'Z') throw PBException("Non Zulu 8601 timezone not supported");
        char* ptr = strptime(iso8601Time.c_str(), "%FT%T", &t);
        if( ptr == nullptr)
        {
            throw PBException("strptime failed, can't parse " + iso8601Time);
        }
        double t2 = timegm(&t); // UTC
        if (*ptr)
        {
            double fraction = atof(ptr);
            t2 += fraction;
        }
        return t2;
    }
    

提交回复
热议问题