Here's an example adapted from cppreference.com :
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
int main() {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::cout << "The time was just "
<< std::put_time(std::localtime(&now_c), "%F %T") << '\n';
}
I don't like this. I want to print my time point without having to go through time_t
. Can I do so...:
put_time
supports?Notes:
Howard Hinnant's library - which has been voted to become part of C++20 - also supports put_time
-like formatting.
#include "date/date.h"
#include <iostream>
int
main()
{
std::cout << date::format("%m/%d/%Y %I:%M:%S %p\n", std::chrono::system_clock::now());
}
Example output:
07/22/2018 03:30:35.001865 AM
A partial solution which doesn't allow you a choice of printing format or timezone, thanks to @inf's suggestion, is found in this answer: you can simply pipe a timepoint to the standard output to get a UTC timestamp string for it:
std::cout << std::chrono::system_clock::now() << " UTC\n";
but the question remains open for arbitrary formats.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With