std::mktime and timezone info

后端 未结 12 535
忘了有多久
忘了有多久 2020-11-30 10:56

I\'m trying to convert a time info I reveive as a UTC string to a timestamp using std::mktime in C++. My problem is that in / &

12条回答
  •  萌比男神i
    2020-11-30 11:29

    I've just been trying to figure out how to do this. I'm not convinced this solution is perfect (it depends on how accurately the runtime library calculates Daylight Savings), but it's working pretty well for my problem.

    Initially I thought I could just calculate the difference between gmtime and localtime, and add that on to my converted timestamp, but that doesn't work because the difference will change according to the time of year that the code is run, and if your source time is in the other half of the year you'll be out by an hour.

    So, the trick is to get the runtime library to calculate the difference between UTC and local time for the time you're trying to convert.

    So what I'm doing is calculating my input time and then modifying that calculated time by plugging it back into localtime and gmtime and adding the difference of those two functions:

    std::tm     tm;
    
    // Fill out tm with your input time.
    
    std::time_t basetime = std::mktime( &tm );
    std::time_t diff;
    
    tm = *std::localtime( &basetime );
    tm.tm_isdst = -1;
    diff = std::mktime( &tm );
    
    tm = *std::gmtime( &basetime );
    tm.tm_isdst = -1;
    diff -= std::mktime( &tm );
    
    std::time_t finaltime = basetime + diff;
    

    It's a bit of a roundabout way to calculate this, but I couldn't find any other way without resorting to helper libraries or writing my own conversion function.

提交回复
热议问题