[英]c++ converting a string containing UTC date & time to a tm struct
我有以下需要UTC的功能? 格式化的字符串,应将其转换为tm结构。
tm utc_string_to_dt(std::wstring sTime)
{
static const std::wstring dateTimeFormat{ L"%Y-%m-%dT%H:%M:%S" };
std::wstringstream ss{ sTime };
std::tm dt;
ss >> std::get_time(&dt, dateTimeFormat.c_str());
// corrections to the returned values. Brain dead year counts from 1900
dt.tm_year = dt.tm_year + 1900; // year counted from 1900
dt.tm_mon = dt.tm_mon + 1; // month starts from 0 (not 1)
return dt;
}
如果我给它一个字符串'2011-09-30T19:46:01.000Z',我得到的日期和时间是2011年9月30日19:46:01,但是如果它得到一个字符串“ 2011-08-30T10:00:00 +01:00我回到2011年8月30日00:00:00-时间部分设置为午夜,如何准确转换后一个字符串。我在Windows上使用VS2013。
您如何输出它/检查值是什么,以及在计算机上设置的时区是什么?
我没看到你所看到的。 鉴于此代码,您对此做了一些修改:
const std::wstring dateTimeFormat{ L"%Y-%m-%dT%H:%M:%S" };
tm utc_string_to_dt(std::wstring sTime)
{
std::wstringstream ss{ sTime };
std::tm dt;
ss >> std::get_time( &dt, dateTimeFormat.c_str() );
return dt;
}
int main()
{
tm x = utc_string_to_dt( L"2011-08-30T10:00:00+01:00" );
std::cout << x.tm_year + 1900 << '/' << x.tm_mon + 1 << '/' << x.tm_mday << "\n"
<< x.tm_hour << ':' << x.tm_min << ':' << x.tm_sec << "\n";
std::wcout << std::put_time( &x, dateTimeFormat.c_str() );
return 0;
}
这是输出:
2011/8/30
10:0:0
2011-08-30T10:00:00
我怀疑输出方法正在调整时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.