如何将UTC中的C ++计时时间转换为UTC中的字符串?
因为在我的测试中,将计时时间转换为字符串时使用的是不同的时区。
示例:
#include <iostream>
#include <string>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <cstdint>
#include <ctime>
std::string getStringFromDateTime(const std::chrono::system_clock::time_point & value) {
std::time_t time_now_t = std::chrono::system_clock::to_time_t(value);
std::tm now_tm = *std::localtime(&time_now_t);
char buf[512];
std::strftime(buf, 512, "%Y-%m-%d %H:%M:%S %z", &now_tm);
return buf;
}
std::string getStringFromDateTimeWithGmtime(const std::chrono::system_clock::time_point & value) {
std::time_t time_now_t = std::chrono::system_clock::to_time_t(value);
std::tm now_tm = *std::gmtime(&time_now_t);
char buf[512];
std::strftime(buf, 512, "%Y-%m-%d %H:%M:%S %z", &now_tm);
return buf;
}
int main()
{
std::tm tm = {};
std::stringstream ss("2018-12-07 20:00:00"); // example of UTC time at 20hs
ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
auto dt = std::chrono::system_clock::from_time_t(std::mktime(&tm));
std::cout << (dt.time_since_epoch().count() / 1000000) << " - EPOCH" << std::endl;
// 1544212800 - 20:00 - correct (in utc)
// 1544180400 - 11:00 - wrong (returned by count)
std::cout << getStringFromDateTime(dt) << " - NORMAL" << std::endl;
std::cout << getStringFromDateTimeWithGmtime(dt) << " - GMTIME" << std::endl;
return EXIT_SUCCESS;
}
我也有一个魔盒:
https://wandbox.org/permlink/Bm9c9FCtfP0hCAUn
结果是:
1544180400 - EPOCH
2018-12-07 20:00:00 +0900 - NORMAL
2018-12-07 11:00:00 +0000 - GMTIME
我希望该字符串也以UTC格式存储日期/时间,与我创建的日期/时间相同(“ 2018-12-07 20:00:00”)。
有人可以帮助我吗?