Convert from a broken down date time structure from UTC to localtime in C++.
See Stackoverflow: How to convert from UTC to local time in C?
I converted the code from C to C++ and make it shorter.
// replace non std function strptime with std::get_time
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ctime>
/*
Convert from a broken down date time structure from UTC to localtime.
See https://stackoverflow.com/questions/9076494/how-to-convert-from-utc-to-local-time-in-c
*/
std::tm UTC2localtime(std::tm tp) {
// make sure Daylight saving time flag is not accidentally switched on in UTC time
tp.tm_isdst = 0;
// get seconds since EPOCH for this time
const time_t utc = std::mktime(&tp);
std::cout << "UTC date and time in seconds since EPOCH: " << utc << "\n";
// convert UTC date and time (Jan. 1, 1970) to local date and time
std::tm e0{};
e0.tm_mday = 1;
e0.tm_year = 70;
// get time_t EPOCH value for e0. This handles daylight saving stuff.
// The value is e.g. -3600 for 1h difference between the timezones
const time_t diff = std::mktime(&e0);
// calculate local time in seconds since EPOCH
const time_t local = utc - diff;
std::cout << "local date and time in seconds since EPOCH: " << local << "\n";
// convert seconds since EPOCH for local time into local_tm time structure
std::tm local_tm;
if(localtime_r(&local, &local_tm) == nullptr) {
throw std::system_error(errno, std::generic_category(), "UTC2localtime(): in conversion vom UTC to localtime");
}
return local_tm;
}
int main() {
// hard coded date and time in UTC
std::string datetime = "2013 11 30 23 30 26";
std::cout << "UTC date and time to be converted in local time: " << datetime << "\n";
// put values of datetime into time structure
std::tm UTC_tm{};
std::istringstream ss(datetime);
ss >> std::get_time(&UTC_tm, "%Y %m %d %H %M %S");
if(ss.fail()) {
throw std::runtime_error("Can not parse datetime from datetime '" + datetime + "' to format %Y %m %d %H %M %S");
}
const std::tm local_tm = UTC2localtime(UTC_tm);
std::cout << "local date and time: " << std::put_time(&local_tm, "%Y-%m-%d %H:%M:%S %Z") << "\n";
}