Reputation: 7593
I'm trying to print a timestamp like this.
2018-05-24T20:16:07.339271
I don't want to use Boost or any third party libraries. I want to only use the standard library. I'm using Clang 6, so I should be able to use C++ 17 if necessary.
I started looking at chrono
and have something like this.
auto now = std::chrono::high_resolution_clock::now();
But, I'm unsure how to get the datetime format that I want from above.
Upvotes: 4
Views: 1726
Reputation: 1400
The following code uses standard C++ only. The data contained in *loc_time and milli_secs can be used to produce the desired output in local time. To get the output in UTC, use std::gmtime instead of std::localtime.
// get actual system time
const auto now = std::chrono::system_clock::now();
// get seconds since 1970/1/1 00:00:00 UTC
const auto sec_utc = std::chrono::system_clock::to_time_t(now);
// get pointer to tm struct (not thread safe!)
const auto loc_time = std::localtime(&sec_utc);
// get time_point from sec_utc (note: no milliseconds)
const auto now_s = std::chrono::system_clock::from_time_t(sec_utc);
// get milliseconds (difference between now and now_s
const auto milli_secs = std::chrono::duration<double, std::milli>(now - now_s).count() * .001;
Upvotes: 2
Reputation: 161
standard library c++ does not provide a proper date type, so you can use
structs and functions from c which is inherited on c++. <ctime> header
file need to include in c++ program. i think below code will help you.
time_t now = time(0);
cout<<now<<endl;
tm *lt = localtime(&now);
Upvotes: -3