In a program of mine I have to read in times in several different formats. In all formats however the time is given in UTC (i.e. not in my local timezone). What would be the best way for a function that takes the date string and a format string and outputs a std::time_t
timestamp?
Currently I am using boost
#include "boost/date_time/gregorian/gregorian.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
std::time_t to_timestamp_utc(const std::string& _dateString) {
using namespace boost::gregorian;
using namespace boost::posix_time;
return to_time_t(ptime(from_undelimited_string(_dateString)));
}
but this works only for the "YYYYMMDD" format. The standard library function std::get_time
on the other hands assumes the input date to be formatted in my local time not UTC (or at least I haven't found a way to change it yet). Any suggestions are most welcome.
Current Solution based on Maxim Egorushkin suggestion.
std::time_t utc_to_timestamp(const std::string& _dateString, const std::string& _format) {
// Set sec, min, hour to zero in case the format does not provide those
std::tm timeStruct;
timeStruct.tm_sec = 0;
timeStruct.tm_min = 0;
timeStruct.tm_hour = 0;
char* const result = strptime(_dateString.c_str(), _format.c_str(), &timeStruct);
// Throw exception if format did not work
REQUIRE(result == _dateString.c_str()+_dateString.size(), "Failed to parse dateTime.");
return timegm(&timeStruct);
}