I am trying to save std::time_point in std::stream and read it back. One of the problems is that using standard functions "loses" an hour somewhere. Ie, the time I read is 1 hour for the time I write. I suspect that I need to set daylight saving time. I put together a small program that prints the time before std::stringstream and reads it back.
#include <iomanip> #include <iostream> #include <sstream> #include <chrono> #include <ctime> using std::chrono::system_clock; namespace chrono = std::chrono; void test(); int main(int argc, char** argv) { std::stringstream ss; auto start = system_clock::now(); std::time_t ts = system_clock::to_time_t(start); std::tm time_out = *std::localtime(&ts); ss << std::put_time(&time_out, "%Y-%m-%d %H:%M:%S %Z") << '\n'; std::cout << ss.str() << std::endl; std::tm time_in; ss >> std::get_time(&time_in, "%Y-%m-%d %H:%M:%S %Z"); std::cout << "Are time dsts equal? : " << (time_out.tm_isdst == time_in.tm_isdst) << '\n'; std::time_t rawTime = std::mktime(&time_in); auto end = std::chrono::system_clock::from_time_t(rawTime); std::cout << "Are time points equal? : " << (start == end) << '\n'; // print the trouble makers std::time_t start_time = system_clock::to_time_t(start); std::time_t end_time = system_clock::to_time_t(end); std::cout << "times: \n" << '\t' << std::put_time(std::localtime(&start_time), "%c %z") << '\n' << '\t' << std::put_time(std::localtime(&end_time), "%c %z") << '\n'; // this is a source of strange behaviour... // std::cout << "Difference: " // << chrono::duration_cast<chrono::seconds>(start - end).count() // << std::endl; return 0; }
The strangest thing is that the program prints the following:
Are time dsts equal? : 1 Are time points equal? : 0 times: Tue Dec 11 19:26:24 2012 +0000 Tue Dec 11 19:26:24 2012 +0000
And when I uncomment the 3 lines at the end of the program (print the difference between the time points), the result:
Are time dsts equal? : 0 Are time points equal? : 0 times: Tue Dec 11 19:29:40 2012 +0000 Tue Dec 11 18:29:40 2012 +0000 Difference: 3600
Note that dst (daylight saving time) is suddenly not equal, and not a single time.
I am using libC ++ on Mac OS X 10.8.2 with XCode46-DP2. The clang ++ versions I use are Apple clang version 4.1 and clang version 3.2 (trunk 167239)
I think my questions are: A) Regarding the 1 hour difference, is this a mistake in my library, or am I not using standard functions correctly? (The latter will not surprise me ...)
B) What happens to the code when I uncomment the three lines at the end of my program? This seems like a mistake. Does anyone want to try it on their platform?
source share