Reputation: 2593
How to get UTC time in micro-seconds with leap seconds adjusted?
I am using boost::universal_clock()
boost::posix_time::time_duration utc_time =
boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::from_time_t(0);
int64_t total_microsec = utc_time.total_microseconds();
But the result of this is same as
std::chrono::time_point_cast<std::chrono::duration<int64_t, std::microseconds>>(
std::chrono::system_clock::now())
.time_since_epoch()
.count();
which seems that boost is not adjusting leap seconds. However when I use C gmtime()
I get different result:
time_t mytime;
struct tm *ptm;
time(&mytime); // Get local time in time_t
ptm = gmtime(&mytime); // Find out UTC time
time_t utctime = mktime(ptm); // Get UTC time as time_t
How to achieve it using boost library?
Upvotes: 1
Views: 495
Reputation: 219518
Using Howard Hinnant's date/time library this is very easy:
#include "date/tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
auto now = floor<microseconds>(utc_clock::now());
cout << now << '\n';
cout << now.time_since_epoch() << '\n';
cout << clock_cast<system_clock>(now).time_since_epoch() << '\n';
}
This is a preview of the C++20 additions to <chrono>
, but in namespace date
.
utc_clock
counts time since 1970-01-01 00:00:00 UTC including leap seconds. The clock_cast
casts the time_point
from this clock back to that of system_clock
just for comparison purposes.
This program just output for me:
2019-08-10 00:19:04.388788
1565396371388788µs
1565396344388788µs
Upvotes: 1