【问题标题】:how is checking dates in C#如何在 C# 中检查日期
【发布时间】:2023-03-19 21:06:01
【问题描述】:

我有 2 个日期:date1date2;我想检查另一个日期是否在 date1 和 date2 之间,非常感谢

【问题讨论】:

  • 回复:当前的答案,除非您知道date1date2 的顺序,否则您需要在将其与anotherDate'进行比较之前对其进行排序。

标签: c#


【解决方案1】:

这很简单:

if (date3 >= date1 && date3 <= date2)

【讨论】:

    【解决方案2】:

    您可以只使用标准的 、>= 和

    if( someDate >= date1 && someDate <= date2 )
    {
    }
    

    而且,您可以为它制作自己的扩展方法:

    public static class DateExtensions
    {
        public static bool Between( this DateTime d, DateTime start, DateTime end )
        {
            return d >= start && d <= end;
        }
    }
    

    你可以这样使用:

    DateTime someDate = new DateTime (2012, 5, 6);
    
    if( someDate.Between (date1, date2) )
    {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 2012-06-04
      相关资源
      最近更新 更多