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

标签 c++ windows visual-studio-2010 time utc

如何获取当前时间作为 W3C UTC 时间字符串,如 W3C Date and Time Formats (Profile of ISO 8601) 中所述?

具体来说,这是我所追求的格式:

yyyy-mm-ddThh:mm:ssZ

例子:

2013-05-24T20:07:47Z

注意:我使用的是 Visual Studio 2010

最佳答案

这是我的解决方案。 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();
}

关于C++:获取当前时间作为 W3C UTC 时间字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16743262/

相关文章:

c# - 如何使用 sqlite 创建 asp.net web 应用程序

c++ - 什么可以是子表达式?

c++ - 使用 'goto' 时是否清除了所有内容?

visual-studio-2010 - Visual Studio 2010 - 大括号自动对齐已更改,如何修复此问题?

php - 如何安装依赖wamp的php?

php - 安装 php_svn windows & linux

c# - 如何更改太大的文件(收到来自 StyleCop 的警告)?

c++ - C++ 类实例化可以在运行时更改其大小吗

c++ - 如何初始化或将中文赋给wstring?

Java检查Windows上是否安装了程序