【问题标题】:How to check if DateTime.Now is between two given DateTimes for time part only?如何检查 DateTime.Now 是否仅在时间部分的两个给定 DateTimes 之间?
【发布时间】:2020-10-23 18:12:28
【问题描述】:

对于我的应用,我需要知道 Now() 是否介于两个值之间。

用户可以设置开始和结束时间,这样他就不会被通知打扰(例如在夜间)。

所以如果有两个TimePickers(开始时间和结束时间),用户可以设置。

假设用户将22:00 设置为StartTime,将07:00 设置为EndTime(这将覆盖整个夜晚)。

如何检查DateTime.Now 是否在选定的开始时间和结束时间之间?

编辑: 我只希望它与小时和分钟部分一起使用。因此,如果用户设置了开始和结束时间,这应该适用于每晚。

【问题讨论】:

  • 恐怕在六个答案中,我的答案似乎适用于您的示例时间。
  • 您能详细说明原因吗?

标签: c#


【解决方案1】:

首先您需要将所有内容转换为相同的单位(我们将使用TimeSpan),然后您需要查看起止时间是否超过午夜,最后根据检查结果进行比较:

// convert everything to TimeSpan
TimeSpan start = new TimeSpan(22, 0, 0);
TimeSpan end = new TimeSpan(07, 0, 0);
TimeSpan now = DateTime.Now.TimeOfDay;
// see if start comes before end
if (start < end)
    return start <= now && now <= end;
// start is after end, so do the inverse comparison
return !(end < now && now < start);

这里有一个函数可以帮你完成:

bool TimeBetween(DateTime datetime, TimeSpan start, TimeSpan end)
{
    // convert datetime to a TimeSpan
    TimeSpan now = datetime.TimeOfDay;
    // see if start comes before end
    if (start < end)
        return start <= now && now <= end;
    // start is after end, so do the inverse comparison
    return !(end < now && now < start);
}

你可以这样称呼它:

bool silenceAlarm = TimeBetween(DateTime.Now, StartTime.Value, EndTime.Value);

【讨论】:

  • 非常好。谢谢加布。
【解决方案2】:

由于您只收集两次没有日期,因此您需要确定这两次是否来自同一天。如果将StartTimeEndTimeNow 放入TimeSpans

if (StartTime > EndTime) 
{
    // the range crosses midnight, do the comparisons independently
    return (StartTime < Now) || (Now < EndTime);
}
else 
{
    // the range is on the same day, both comparisons must be true
    return StartTime < Now && Now < EndTime;
}

【讨论】:

    【解决方案3】:
        public static bool isCurrenctDateBetween(DateTime fromDate, DateTime toDate)
        {
            DateTime curent = DateTime.Now.Date;
            if (fromDate.CompareTo(toDate) >= 1)
            {
                MessageBox.Show("From Date shouldn't be grater than To Date", "DateRange",MessageBoxButton.OKCancel, MessageBoxImage.Warning);
            }
            int cd_fd = curent.CompareTo(fromDate);
            int cd_td = curent.CompareTo(toDate);
    
            if (cd_fd == 0 || cd_td == 0)
            {
                return true;
            }
    
            if (cd_fd >= 1 && cd_td <= -1)
            {
                return true;
            }
            return false;
        }
    

    【讨论】:

      【解决方案4】:
      DateTime nowDate = DateTime.Now;
      // set these to today + time from time picker
      DateTime startDate = new DateTime(nowDate.Year, nowDate.Month, nowDate.Day,
          selectedStart.Hour, selectedStart.Minute, 0);
      DateTime endDate = new DateTime(nowDate.Year, nowDate.Month, nowDate.Day, 
          selectedEnd.Hour, selectedEnd.Minute, 0);
      bool isBetween = nowDate < endDate && nowDate > startDate;
      

      2016 年 6 月 8 日更新
      不知道为什么不赞成投票是合适的,因为这是一个可行的解决方案。 OP 确实专门询问了DateTime,但我建议使用TimeSpan,而不是根据@Gabe 的回答。

      根据我的回答,这是一个工作功能:

      public static bool TimeBetween(DateTime check, DateTime start, DateTime end, bool inclusive = true)
      {
          var from = new DateTime(check.Year, check.Month, check.Day, 
              start.Hour, start.Minute, start.Second, start.Millisecond);
          var to = new DateTime(check.Year, check.Month, check.Day, 
              end.Hour, end.Minute, end.Second, end.Millisecond);
      
          if (inclusive)
              return from <= check && to >= check;
      
          return from < check && to > check;
      }
      

      这是一个有效的小提琴:https://dotnetfiddle.net/vZCXqv

      完整代码:

      using System;
      
      public class Program
      {
          public static void Main()
          {
              var start = new DateTime(1, 1, 1, 9, 0, 0);
              var end = new DateTime(1, 1, 1, 17, 0, 0);
      
              Console.WriteLine("{0} - Too early",                TimeBetween(new DateTime(2014, 1, 1, 08, 59, 59, 999), start, end));
              Console.WriteLine("{0} - On start time exclusive",  TimeBetween(new DateTime(2014, 1, 1, 09, 00, 00, 000), start, end, false));
              Console.WriteLine("{0} - On start time inclusive",  TimeBetween(new DateTime(2014, 1, 1, 09, 00, 00, 000), start, end));
              Console.WriteLine("{0} - After start time",         TimeBetween(new DateTime(2014, 1, 1, 09, 00, 00, 001), start, end));        
              Console.WriteLine("{0} - Before end time",          TimeBetween(new DateTime(2014, 1, 1, 16, 59, 59, 999), start, end));
              Console.WriteLine("{0} - On end time inclusive",    TimeBetween(new DateTime(2014, 1, 1, 17, 00, 00, 000), start, end));
              Console.WriteLine("{0} - On end time exclusive",    TimeBetween(new DateTime(2014, 1, 1, 17, 00, 00, 000), start, end, false));
              Console.WriteLine("{0} - Too late",                 TimeBetween(new DateTime(2014, 1, 1, 17, 00, 00, 001), start, end));
          }
      
          public static bool TimeBetween(DateTime check, DateTime start, DateTime end, bool inclusive = true)
          {
              var from = new DateTime(check.Year, check.Month, check.Day, start.Hour, start.Minute, start.Second, start.Millisecond);
              var to = new DateTime(check.Year, check.Month, check.Day, end.Hour, end.Minute, end.Second, end.Millisecond);
      
              if (inclusive)
                  return from <= check && to >= check;
      
              return from < check && to > check;
          }
      }
      

      【讨论】:

      • 不管日期如何,这都能正常工作,对吧?因此,如果用户设置时间和日期,这将始终有效吗?
      • @Niels。正确的。如果您存储“start=Jan 10th 2012 09:00”,上述代码在任何一天仍然有效。
      • 不,请参阅 Gabe 和 yhw42 的回答,@Niels。
      【解决方案5】:

      直接比较。

      如果(日期 > 开始日期 && 日期

      【讨论】:

      • 您如何获得日期?请参阅 Gabe 和 yhw42 的答案。
      【解决方案6】:

      Find if current time falls in a time range的骗子

      DateTime start = new DateTime(2009, 12, 9, 10, 0, 0));
      DateTime end = new DateTime(2009, 12, 10, 12, 0, 0));
      DateTime now = DateTime.Now;
      
      if ((now > start) && (now < end))
      {
         //match found
      }
      

      时间跨度,再次取自欺骗。

      TimeSpan start = new TimeSpan(10, 0, 0);
      TimeSpan end = new TimeSpan(12, 0, 0);
      TimeSpan now = DateTime.Now.TimeOfDay;
      
      if ((now > start) && (now < end))
      {
         //match found
      }
      

      【讨论】:

      • 我认为OP只想使用时间部分,忽略日期部分
      • 这还是不行;请参阅 Gabe 和 yhw42 的答案。
      【解决方案7】:

      我用这个,所以你可以直接传递DateTime:

              public static bool TimeBetween(DateTime time, DateTime startDateTime, DateTime endDateTime)
          {
              // get TimeSpan
              TimeSpan start = new TimeSpan(startDateTime.Hour, startDateTime.Minute, 0);
              TimeSpan end = new TimeSpan(endDateTime.Hour, endDateTime.Minute, 0);
      
              // convert datetime to a TimeSpan
              TimeSpan now = time.TimeOfDay;
              // see if start comes before end
              if (start < end)
                  return start <= now && now <= end;
              // start is after end, so do the inverse comparison
              return !(end < now && now < start);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-07
        • 2022-01-20
        • 2017-11-22
        相关资源
        最近更新 更多