【问题标题】:How to validate date in C# [duplicate]如何在 C# 中验证日期 [重复]
【发布时间】:2014-09-12 08:27:40
【问题描述】:

我想使用两个 (2) 日期选择器在给定日期之间的 2 个月内验证日期

示例:DATEPICKERdatefrom = 02/05/2013 和 DATEPICKERdateto = 03/08/2013 (dd/mm/yyyy)

我的陈述应该是什么?

if ( /*DATEPICKERdatefrom between DATEPICKERdateto is not between 2 months*/ )
{
messagebox.show("the Date must within 2 months")
}
else
{
//GO
}

【问题讨论】:

  • 只需创建您感兴趣的新 DateTime 实例并将其与 > 和 < 运算符进行比较。
  • 您好,StackOverflow 是一个用于解决现有代码问题的网站。要求为您编写代码的问题往往不会被很好地接受。

标签: c# datetime datepicker


【解决方案1】:

这是一个如何偏移日期的示例。

DateTime twoMonthsBack = DateTime.Now.AddMonths(-2);
DateTime twoMonthsLater = DateTime.Now.AddMonths(2);

您可以将示例中的DateTime.Now 替换为您的日期。并且您可以选择对其进行验证。

也许

if(DATEPICKERdateto > DATEPICKERdatefrom.AddMonths(2))
{
    //to date is more than two months from start date
    messagebox.show("the Date must within 2 months");
}
else
{
    //GO
}

以上示例基于从日期始终小于当前日期的假设。

【讨论】:

    【解决方案2】:

    如果这些值为DateTime,您可以简单地使用<或>运算符进行比较。

    if((date > DATEPICKERdatefrom) && (date < DATEPICKERdateto))
    

    这些运算符被DateTime 重载为;

    [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool operator < (DateTime t1, DateTime t2) {
            return t1.InternalTicks < t2.InternalTicks;
    }
    
    
    [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool operator > (DateTime t1, DateTime t2) {
            return t1.InternalTicks > t2.InternalTicks;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-27
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 2012-10-14
      • 1970-01-01
      相关资源
      最近更新 更多