0

I have a function here that attempts to return true if the current time is between two military times.

The issue here is finding a time between 2130 and 0700 is a little tricky. The 2130 works fine, but 0700 is before 2130, so it returns false here. How can I get this to return true?

Just switch the && to a ||?

public bool IsSleeping()
{
    DateTime m_dt = DateTime.Now;
    string strMilitaryTime;
    int time;

    strMilitaryTime = m_dt.ToString("HHmm");    // Get current military time
    time = Convert.ToInt32(strMilitaryTime);    // Convert to int

    // The time must be between sleeping hours of 2400 and 0700.
    if (time >= 2130 && time < 700)
        return true; 

    return false;
}
Filnor
  • 1,290
  • 2
  • 23
  • 28
Phil
  • 137
  • 2
  • 10
  • 1
    "Military time" isn't a thing (or at least, it's a very Americano-centric term). I think you mean 24-hour clock notation, but what timezone? – Dai Aug 29 '17 at 06:53
  • *Just switch the '&&' to a '||'?* Please try it and see. Also you can just: `return (time >= 2130 && time < 700)` – Gilad Green Aug 29 '17 at 06:53
  • Using integers is not ideal, use a `TimeSpan` to represent a time-of-day value. – Dai Aug 29 '17 at 06:53
  • Gilad, tried that initially. If you think of it, if time is 2300, it's not less than 700, so it will return false. – Phil Aug 29 '17 at 06:56
  • @Phil - with `||` it is enough that one of the statements is true :) so for `2300` it will be true for the first and thus return true. In any case Dai's recommendation of using `TimeSpan` is a good one – Gilad Green Aug 29 '17 at 06:58
  • Oh, I was thinking you were using &&. With ||, that's fine. I'm liking the TimeSpan solution. – Phil Aug 29 '17 at 06:59

1 Answers1

2
public static Boolean IsSleeping()
{
    TimeSpan now = DateTime.Now.TimeOfDay;

    TimeSpan before = new TimeSpan(  7,  0, 0 );
    TimeSpan after  = new TimeSpan( 21, 30, 0 );

    return now < before || now > after;
}
Dai
  • 141,631
  • 28
  • 261
  • 374
  • 1
    Please don't dump "fixed" code, explain your approach and why that solves the problem. – CodeCaster Aug 29 '17 at 06:59
  • It's very readable for me. Thanks! Though I would like to know if TimeOfDay returns a 24-hour time or not, but MSDN might answer that. – Phil Aug 29 '17 at 07:00