Visual 2015上的std :: get_time不会在不正确的日期失败 [英] std::get_time on Visual 2015 does not fail on incorrect date
问题描述
我正在Windows上使用Visual Studio 2015执行以下代码。基本上,我使用 std :: get_time
来解析日期,但是当日期无效时,例如,如果一天大于31,似乎并没有在流中设置失败位。
I'm executing the following code on Windows with Visual Studio 2015. Basically I use std::get_time
to parse a date, but when the date is invalid, for example, a day greater than 31, it does not seem to set the fail bit on the stream.
我已经在带有g ++ 5.4.0的Ubuntu上进行了尝试,它设置了失败位并显示解析失败!。这是Windows上的错误,还是我做错了事。
I have tried this on Ubuntu with g++ 5.4.0 and it sets the fail bit and prints "Parsing failed!". Is this a bug on Windows or am I doing something wrong.
预先感谢!
std::string date = "2019-2-37 23:00:00"; // day (37) is wrong.
std::string format = "%Y-%m-%d %H:%M:%S";
std::tm tm_object{};
std::istringstream input(date);
input.imbue(std::locale(std::setlocale(LC_ALL, nullptr)));
input >> std::get_time(&tm_object, format.c_str());
if (input.fail())
{
std::cout << "Parsing failed!";
}
else
{
std::cout << "Parsing ok!\n";
std::cout << "Day is : " << tm_object.tm_mday;
}
推荐答案
您可以使用 Howard Hinnant在Windows上免费的,开放源代码的仅标头日期时间库,可为您提供所需的行为。语法略有不同,并且易于使用,并且与< chrono>
兼容。与C ++标准的时间解析部分相比,它的文档和说明也更好。
You can use Howard Hinnant's free, open-source header-only datetime library on Windows to give you the desired behavior. The syntax is only slightly different, and it is much easier to use, and compatible with <chrono>
. It is also better documented and specified than the time-parsing parts of the C++ standard.
#include "date.h"
#include <iostream>
#include <sstream>
#include <string>
int
main()
{
std::string date = "2019-2-37 23:00:00"; // day (37) is wrong.
std::string format = "%Y-%m-%d %H:%M:%S";
date::sys_seconds tm_object{};
std::istringstream input(date);
input >> date::parse(format, tm_object);
if (input.fail())
{
std::cout << "Parsing failed!";
}
else
{
std::cout << "Parsing ok!\n";
date::year_month_day ymd = date::floor<date::days>(tm_object);
std::cout << "Day is : " << ymd.day();
}
}
输出:
Parsing failed!
该库也可用于g ++ 5.4.0和clang。
This library also works with g++ 5.4.0 and clang.
您还可以将格式
简化为%F%T
,它可以如果需要,也可以以亚秒精度工作。
You can also simplify your format
down to "%F %T"
, and it can also work with subsecond precision if desired.
这篇关于Visual 2015上的std :: get_time不会在不正确的日期失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!