获取当前时间作为W3C UTC时间字符串

C++: Getting the Current Time as a W3C UTC Time String

本文关键字:时间 W3C UTC 字符串 获取      更新时间:2023-10-16

如何将当前时间作为W3C UTC时间字符串记录在W3C日期和时间格式(ISO 8601配置文件)?

具体来说,这是我想要的格式:

yyyy-mm-ddThh:mm:ssZ

的例子:

2013-05-24T20:07:47Z

注意:我使用的是Visual Studio 2010

这是我的解决方案。参考:time(), gmtime_s()

#include <iomanip>
#include <sstream>
#include <time.h>
/**
 * Get the current time as a W3C UTC time string.
 *
 * @return A time string; the empty string if something goes wrong.
 */
std::string GetUTCTimeString(void)
{
    time_t seconds_since_the_epoch;
    struct tm tm_struct;
    errno_t err;
    std::ostringstream buf;
    // Return the time as seconds elapsed since midnight, January 1, 1970,
    // or -1 in the case of an error.
    time(&seconds_since_the_epoch);
    if (seconds_since_the_epoch == -1) {
        return "";
    }
    // Convert the time in seconds to the time structure.
    err = gmtime_s(&tm_struct, &seconds_since_the_epoch);
    if (err) {
        return "";
    }
    // Format the structure as a W3C UTC date/time string with the special
    // UTC designator 'Z'.
    buf
        <<        std::setw(4) << std::setfill('0') << tm_struct.tm_year + 1900
        << "-" << std::setw(2) << std::setfill('0') << tm_struct.tm_mon + 1
        << "-" << std::setw(2) << std::setfill('0') << tm_struct.tm_mday
        << "T" << std::setw(2) << std::setfill('0') << tm_struct.tm_hour
        << ":" << std::setw(2) << std::setfill('0') << tm_struct.tm_min
        << ":" << std::setw(2) << std::setfill('0') << tm_struct.tm_sec
        << "Z";
    return buf.str();
}