在Windows C++; 我在Windows C++代码中工作:

在Windows C++; 我在Windows C++代码中工作:,c++,windows,C++,Windows,我试图解析第三方软件返回的表示日期的字符串,但我想让解析依赖于所使用的语言环境。现在,我要返回的日期是以下格式:“mm-dd-YYYY tt:ss-A”,但是如果我将区域设置切换到类似加拿大的地方,那么我要返回的字符串是“dd-mm-YYYY tt:ss-A” 如您所见,月和日是交换的。是否有方法检索当前区域设置使用的日期格式?或者更好的是,是否有一种方法可以根据用户的区域设置将字符串解析为不同的日期 #include "stdafx.h" #include <iostream> #

我试图解析第三方软件返回的表示日期的字符串,但我想让解析依赖于所使用的语言环境。现在,我要返回的日期是以下格式:“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;
}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
#包括
#包括
int _tmain(int argc,_TCHAR*argv[]
{
//区域1:从当前时间转到特定于区域设置的日期/时间。
std::time\u t ct=std::time(nullptr);
std::tm=*std::localtime(&ct);
//将时间保存在stringstream中,以便以后用作输入
std::stringstream time_str;
时间序列输入(标准::语言环境(“”);
时间\u str在
中有一个。根据需要,您可以使用它的
%x
转换来读取区域设置的标准日期格式


如果这不符合您的格式,您可能需要查看方面。这有一个
date\u order
成员函数,告诉您当前区域设置(mdy、dmy、ymd或ydm)的首选顺序。然后您可以使用它来选择输入的格式(如果您使用
get\u time
time\u get
进行读取,请选择格式字符串)。

对于
put\u time()
get\u time()

对于put_time(),您使用了
“%x%x”
,而对于get_time(),您使用了
“%x,%x”


希望这能有所帮助

在get_time的示例程序中,我一直在默认调用上遇到崩溃,直到我将其更改为:ss.imbue(std::locale(“en-US”);。然后程序由于解析错误而失败。我在哪里可以找到可以传递的有效区域设置>@Flethuseo:这取决于实现来记录它支持的区域设置名称(除了“C”语言环境之外,所有语言环境都需要支持,但这只是默认情况下发生的情况)。当我尝试使用当前区域设置解析字符串时,我遇到了“解析失败”。据我所知,我将使用%x和%x来获取日期和时间,使用区域设置的格式来处理这两件事。我将编辑我的帖子以说明我在这方面的进展。根据格式,任何国家都不使用mm dd YYYY。我最好r要求第三方提供有意义的输出。我现在已经更新了我的程序,使其使用与用户当前区域设置相同的格式。如果我传递的字符串与我用std::put_time(&tm,“%x%x”)打印的字符串相同,我不明白为什么解析失败;