[英]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.