Ask Your Question
0

What is the method to get a printable output of a C++11 time_point?

asked 2021-04-25 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-06-07 03:00:00 +0000

lakamha gravatar image

One method to get a printable output of a C++11 timepoint is to use the std::puttime function in combination with a std::tm structure.

Here's an example code snippet:

#include <iostream>
#include <iomanip>
#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::tm* now_tm = std::localtime(&now_c);

    std::cout << "Current date and time: " << std::put_time(now_tm, "%c") << '\n';

    return 0;
}

In this example, we first obtain the current system time as a timepoint using std::chrono::systemclock::now(). We then convert this timepoint to a timet value using std::chrono::systemclock::totimet(). This timet value can be used to obtain a std::tm structure using std::localtime(). Finally, we use std::put_time() to format the std::tm structure as a printable output. The "%c" format specifier represents the preferred date and time representation for the current locale.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-25 11:00:00 +0000

Seen: 25 times

Last updated: Jun 07 '22