使用 C++11 chrono 将 ISO8601 UTC 时间作为 std::string
你想使用 C++11 标准的 chrono 库生成 ISO8601 格式的时间戳作为 std::string,例如 2018-03-30T16:51:00Z
解决方案
你可以使用此函数,它使用 std::put_time 和 std::ostringstream 生成结果 std::string。
#include
iso8601_time.cpp
#include <iostream>
#include <chrono>
#include <iomanip>
#include <sstream>
/**
* 生成 UTC ISO8601 格式的时间戳
* 并返回为 std::string
*/
std::string currentISO8601TimeUTC() {
auto now = std::chrono::system_clock::now();
auto itt = std::chrono::system_clock::to_time_t(now);
std::ostringstream ss;
ss << std::put_time(gmtime(&itt), "%FT%TZ");
return ss.str();
}
// 用法示例
int main() {
std::cout << currentISO8601TimeUTC() << std::endl;
}Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow