【发布时间】:2016-01-11 23:14:20
【问题描述】:
我正在使用 Windows C++ 代码:
我正在尝试解析由 3rd 方软件返回的表示日期的字符串,但我想让该解析取决于所使用的语言环境。现在,我返回的日期格式如下:“mm-dd-YYYY tt:ss A”,但如果我将语言环境切换到加拿大,那么我返回的字符串是“dd -mm-YYYY tt:ss A"
如您所见,月份和日期被交换了。有没有办法检索当前语言环境使用的日期格式?甚至更好,有没有办法根据用户的语言环境将字符串解析为不同的日期?
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>
#include <ctime>
#include <sstream>
int _tmain(int argc, _TCHAR* argv[])
{
// Region 1: Go from current time to locale-specific date / time.
std::time_t ct = std::time(nullptr);
std::tm tm = *std::localtime(&ct);
// Save the time in a stringstream to be later used as input
std::stringstream time_str;
time_str.imbue(std::locale(""));
time_str << std::put_time(&tm, "%x %X");
// print the saved stringstream
std::cout << std::locale("").name().c_str() << ": " << time_str.str() << "\n";
// Region 2: Parse from a local-specific date and time string to time (Parsing is failing)
std::tm t = {};
std::istringstream iss(time_str.str().c_str());
iss.imbue(std::locale(""));
iss >> std::get_time(&t, "%x, %X"); // I would expect this to parse my string above correctly.
if (iss.fail()) {
std::cout << "Parse failed\n";
}
else {
std::cout << std::asctime(&t) << '\n';
}
return 0;
}
【问题讨论】:
-
根据en.wikipedia.org/wiki/Date_format_by_country 格式 mm-dd-YYYY 不被任何国家使用。我最好请第 3 方提供有意义的输出。
-
我现在更新了我的程序以使用与用户当前区域设置相同的格式。我不明白为什么解析失败,如果我传递的字符串与我用 std::put_time(&tm, "%x %X"); 打印的字符串相同