【问题标题】:How to validate whether an input date is with in an date interval?如何验证输入日期是否在日期间隔内?
【发布时间】:2019-03-18 13:35:30
【问题描述】:

我正在使用 c 语言,我们现在的课程是关于结构的。这是我的代码的一部分,“temp”是一个结构,其中也有一个日期结构。但是,在某些情况下,某些有效日期直到最后一个条件才能进入。

if( temp.Date.year >= start.year &&  temp.Date.year <= end.year)    
if( (temp.Date.year >= start.year &&  temp.Date.year <= end.year) && (temp.Date.month >= start.month &&  temp.Date.month <= end.month) )    
if( (temp.Date.year >= start.year &&  temp.Date.year <= end.year) && (temp.Date.month >= start.month &&  temp.Date.month <= end.month) && temp.Date.day >= start.day &&  temp.Date.day <= end.day)
                        isDateValid = 1;

【问题讨论】:

  • 请了解格式化stackoverflow.com/editing-help、缩进和制作minimal reproducible example
  • "在某些情况下,某些有效日期直到最后一个条件才能进入" --> 发布这些情况比仅说某些情况存在更能提供信息。发布麻烦案例的价值会增加问题的价值。

标签: c date dateinterval


【解决方案1】:

使用 KISS 方法。保持小而简单。

您可以使用奇怪的条件序列,或者只是将您的日期转换为更方便的东西。

unsigned long start = start.Date.Year * 10000ul + start.Date.month * 100 + start.Date.day;

对 temp 和 end 执行相同操作。

这将为我们提供一些可以轻松比较的数值 YYYYMMDD。

if (start <= temp && temp <= end)
    isValid = true;

虽然这似乎是关于结构的练习,但您可能会将结构的使用限制为提取值。

【讨论】:

  • unsigned long 与简单地使用 unsigned 相比没有什么好处,除非 RHS 也使用 unsinged long 数学。建议start.Date.Year * 10000 --> start.Date.Year * 10000ul.
猜你喜欢
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
  • 2013-05-04
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多