Reputation: 5647
I'm looking to print hh:mm:ss.uuuuuu
timestamps in C++. It seems like I need to use the chrono library and std::chrono::use high_resolution_clock::now()
?
I'm unsure how to proceed from here however.
Upvotes: 1
Views: 701
Reputation: 218700
This is easily accomplished with this C++20 chrono preview library which works with C++11/14/17:
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
cout << format("%T", floor<microseconds>(system_clock::now())) << '\n';
}
Just output for me:
19:31:54.033196
This will port to C++20 by:
#include "date/date.h"
using namespace date;
"%T"
to "{:%T}"
This is a header-only, open-source library.
The output is UTC. If you need local time, that is available too, but the library is not header-only. It is at the same link and would be used like this:
#include "date/tz.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
zoned_time zt{current_zone(), floor<microseconds>(system_clock::now()))};
cout << format("%T", zt) << '\n';
}
The above syntax uses C++17. If you're using C++11 or 14 change zoned_time
to zoned_time<microseconds>
.
Some installation is required for the tz.h library.
Upvotes: 2