在 Windows C++ 中将字符串解析为日期的区域设置感知

Locale-aware parsing of strings to dates in Windows C++

本文关键字:日期 区域 感知 设置 C++ Windows 字符串      更新时间:2023-10-16

我正在使用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 failedn";
    }
    else {
        std::cout << std::asctime(&t) << 'n';
    }
    return 0;
}

<iomanip> 中有一个std::get_time。根据所需的内容,您可以使用其%x转换来读取区域设置的标准日期格式。

如果这不符合您的格式,您可能需要查看time_get方面。它有一个date_order成员函数,告诉您当前语言环境(mdy、dmy、ymd 或 ydm(的首选排序。然后,您可以使用它来选择输入的格式(如果您使用 get_timetime_get 进行读取,请选择格式字符串(。

您没有对put_time()get_time()使用相同的格式

对于 put_time((,您使用"%x %X",而对于 get_time((,您使用"%x, %X"

希望这有帮助