How to check if DateTime.Now is between two given DateTimes for time part only?
First you need to convert everything to the same units (we'll use TimeSpan
), then you need to see whether the start-end times cross midnight, and finally do your comparison based on the results of that check:
// 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);
Here's a function to do it for you:
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);
}
You would call it like:
bool silenceAlarm = TimeBetween(DateTime.Now, StartTime.Value, EndTime.Value);
Since you are only gathering two times without dates, you need to figure out if the two times are from the same day or not. If you put the StartTime
, EndTime
, and Now
into 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;
}
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;
}