C++ 检查日期是否有效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9436697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:49:53  来源:igfitidea点击:

C++ check if a date is valid

c++datetime

提问by MBZ

is there any function to check if a given date is valid or not? I don't want to write anything from scratch.

是否有任何功能可以检查给定日期是否有效?我不想从头开始写任何东西。

e.g. 32/10/2012 is not valid and 10/10/2010 is valid

例如 32/10/2012 无效而 10/10/2010 有效

采纳答案by spencercw

If your string is always in that format the easiest thing to do would be to split the string into its three components, populate a tmstructure and pass it to mktime(). If it returns -1 then it's not a valid date.

如果您的字符串始终采用该格式,最简单的做法是将字符串拆分为其三个部分,填充一个tm结构并将其传递给mktime(). 如果它返回 -1,那么它不是一个有效的日期。

You could also use Boost.Date_Timeto parse it:

您还可以使用Boost.Date_Time来解析它:

string inp("10/10/2010");
string format("%d/%m/%Y");
date d;
d = parser.parse_date(inp, format, svp);

回答by Alikar

The boost date time class should be able to handle what you require. See http://www.boost.org/doc/libs/release/doc/html/date_time.html

提升日期时间类应该能够处理您的需求。请参阅http://www.boost.org/doc/libs/release/doc/html/date_time.html

回答by netcoder

If the format of the date is constant and you don't want to use boost, you can always use strptime, defined in the ctimeheader:

如果日期的格式是常量并且您不想使用 boost,则可以始终使用strptime, 在ctime标题中定义:

const char date1[] = "32/10/2012";
const char date2[] = "10/10/2012";
struct tm tm;

if (!strptime(date1, "%d/%m/%Y", &tm)) std::cout << "date1 isn't valid\n";
if (!strptime(date2, "%d/%m/%Y", &tm)) std::cout << "date2 isn't valid\n";

回答by Jim Fell

If the slashes are inserted programatically (I would assume so, since you're assuming that they'll always be there.), it would probably be best to validate the month, day, and year separately. For example:

如果以编程方式插入斜杠(我会这样假设,因为您假设它们将始终存在。),最好分别验证月、日和年。例如:

if ( (month < 1) || (month > 12) ) return false;