Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One approach to creating an ISO 8601 datetime format in C++ is to use the std::put_time function that is part of the C++ Standard Library. Here is an example code snippet that demonstrates this approach:

#include <iostream>
#include <iomanip>
#include <chrono>

int main() {
    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    std::time_t time = std::chrono::system_clock::to_time_t(now);

    struct tm local_tm;
    localtime_s(&local_tm, &time);

    char buffer[50];
    std::strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%S%z", &local_tm);

    std::cout << buffer << std::endl;

    return 0;
}

In this example, we first create a system_clock::time_point object representing the current time, and then convert it to a time_t object. We use the localtime_s function to get the local time as a tm struct, which we then pass to the strftime function to format it according to the ISO 8601 standard. Finally, we print the resulting string to the console.

Note that the %z format specifier in the strftime call gives the timezone offset in the format of +HHMM or -HHMM, depending on whether it is east or west of GMT. This is not strictly required for ISO 8601, but is a common convention.

There are other ways to achieve the same result, such as using libraries like Boost or strftime.net, or manually formatting the string using string manipulation operations.