在 Windows C++ 中将字符串解析为日期的区域设置感知
Locale-aware parsing of strings to dates in Windows C++
我正在使用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_time
或 time_get
进行读取,请选择格式字符串(。
您没有对put_time()
和get_time()
使用相同的格式
对于 put_time((,您使用"%x %X"
,而对于 get_time((,您使用"%x, %X"
希望这有帮助
相关文章:
- 查询SQLite数据库中的日期
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- Log4cpp:以UTC/GMT时区打印日期
- 使用C++的日期库读取时间
- 将QGraphicsItem的移动区域限制在多边形区域内
- 日期格式为C++
- 如何在 C++20 计时中为日期添加天数?
- 有没有一种优雅而快速的方法来测试整数中的 1 位是否位于连续区域
- 如何在QTableView中排序和更改日期格式
- 如何在cpp中使用地图显示给定日期范围内(在下面的问题中)的费率?
- Gtkmm 会不断检查 Gtk::日历上的所选日期是否发生变化
- 在 Linux 中存储区域设置名称的缓冲区大小应该是多少?
- 两个连续的 OpenMP 并行区域会相互减慢速度
- 提升区域设置规范化带状字符,但不规范化重音
- fmt 与 Howard Hinnant 的日期:为什么从 fmt::to_string "{}"?FMT 和日期的最佳实践?
- 使程序检查当前日期是否=预期日期
- 使用UTC来回转换日期以忽略DST但仍使用当前用户的有效区域设置是否安全
- 使用不同的区域设置提取年、月和日期
- 在 Windows C++ 中将字符串解析为日期的区域设置感知
- 构造日期的区域设置与当前区域设置不同