I have followed some good answers to similar questions like this one.
Yet my code seems to give output one hour later after converting string to time_point and back to string.
The code that gives the wrong answer:
#include <string>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
using date_time = std::chrono::system_clock::time_point;
std::string dateTimeToString(date_time time) {
std::time_t now_c = std::chrono::system_clock::to_time_t(time);
auto tm = std::localtime(&now_c);
char buffer[32];
std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", tm);
return std::string(buffer);
}
date_time stringToDateTime(const std::string &s) {
std::tm timeDate = {};
std::istringstream ss(s);
ss >> std::get_time(&timeDate, "%Y-%m-%d %H:%M:%S");
return std::chrono::system_clock::from_time_t(mktime(&timeDate));
}
int main() {
std::string birthday = "2000-06-05 20:20:00";
std::cout << "Two birthday dates: \n" << birthday << " \nsecond one:\n" << dateTimeToString(stringToDateTime(birthday))
<< "\n******************\n";
return 0;
}
And the output:
Two birthday dates: 2000-06-05 20:20:00 second one: 2000-06-05 21:20:00
I have thought that this has something to do with timezones, but I am unable to solve this problem. What is wrong with my code?