Determine if time falls within the specified hour range

I am new to C #. I would like to check if the time is between two given hours, and if so, then do something. Can someone give me an example?

Pseudo-code example:

int starthour = 17;
int endhour = 2;

if ( hour between starthour and endhour){
    dosomething();
}

How to write a check, is it hourbetween starthourand endhour? In C #, time is returned in AM / PM format, so I don’t know if it will understand the number 17as “5 PM”.

+3
source share
7 answers

Assuming you are talking about current time, I would do something like this:

// Only take the current time once; otherwise you could get into a mess if it
// changes day between samples.
DateTime now = DateTime.Now;
DateTime today = now.Date;
DateTime start = today.AddHours(startHour);
DateTime end = today.AddHours(endHour);

// Cope with a start hour later than an end hour - we just
// want to invert the normal result.
bool invertResult = end < start;

// Now check for the current time within the time period
bool inRange = (start <= now && now <= end) ^ invertResult;
if (inRange)
{
    DoSomething();
}

Adjust <=in the latter condition, so that your borders are inclusive / exclusive.

, , , , "" .

+16

, , , 0 23 0, , :

(start <= end && start <= t && t <= end) or (start > end && (start <= t || t <= end))

, , , if-else, , start <= end , t - , . - , t , , , . , , , , :

  • NOT ( < t & t < )

:

  • NOT ( < t) NOT (t < start)
  • NOT (t < start) NOT (end < t)
  • t >= >= t
  • start <= t t <= end

.

@JonSkeet

, , , 1:00, 1- .

  • 1- 1
  • 1
  • 5 . 1 ( ).
  • 2 1 ( )
  • 2 2 ( a > )

, , ≰ , 5 1- , 1- 1, , , 1am, 1:00 17:00 2 . - ?

@

, , , 1am, 22:00 (22:00), :

  • - 17
  • End is 26
  • 22 + 24 = 46! .

, ! , Google, .

+3

DateTime s TimeSpan, , (TotalHours :

TimeSpan ts = starttime - endtime;
if(ts.TotalHours > 2)
{
  dosomething();
}

, , TotalMilliseconds - DateTime s 0.

+2

, , java.

        //Initialize now, sleepStart, and sleepEnd Calendars
        Calendar now = Calendar.getInstance();
        Calendar sleepStart = Calendar.getInstance();
        Calendar sleepEnd = Calendar.getInstance();

        //Assign start and end calendars to user specified star and end times
        long startSleep = settings.getLong("startTime", 0);
        long endSleep = settings.getLong("endTime", 0);
        sleepStart.setTimeInMillis(startSleep);
        sleepEnd.setTimeInMillis(endSleep);

        //Extract hours and minutes from times
        int endHour = sleepEnd.get(Calendar.HOUR_OF_DAY);
        int startHour = sleepStart.get(Calendar.HOUR_OF_DAY);
        int nowHour = now.get(Calendar.HOUR_OF_DAY);
        int endMinute = sleepEnd.get(Calendar.MINUTE);
        int startMinute = sleepStart.get(Calendar.MINUTE);
        int nowMinute = now.get(Calendar.MINUTE);

        //get our times in all minutes
        int endTime = (endHour * 60) + endMinute;
        int startTime = (startHour * 60) + startMinute;
        int nowTime = (nowHour * 60) + nowMinute;

    /*****************What makes this 100% effective***************************/
        //Test if end endtime is the next day
        if(endTime < startTime){
            if(nowTime > 0 && nowTime < endTime)
                nowTime += 1440;
            endTime += 1440;
        }
    /**************************************************************************/

        //nowTime in range?
        boolean inRange = (startTime <= nowTime && nowTime <= endTime);

        //in range so calculate time from now until end
        if(inRange){
            int timeDifference = (endTime - nowTime);
            now.setTimeInMillis(0);
            now.add(Calendar.MINUTE, timeDifference);
            sleepInterval = now.getTimeInMillis() / 1000;
            editor.putBoolean("isSleeping", true);
            editor.commit();
            Log.i(TAG, "Sleep Mode Detected");
            returned = true;
        }
+1
bool CheckHour(DateTime check, DateTime start, DateTime end)
{
    if (check.TimeOfDay < start.TimeOfDay)
        return false;
    else if (check.TimeOfDay > end.TimeOfDay)
        return false;
    else
        return true;
}
0
int starthour = 17;
int endhour = 2;
int nowhour = DateTime.Now.Hour;

if (endhour < starthour)
{
    endhour+=24;
    nowhour+=24;
}

if (starthour <= nowhour && nowhour <= endhour)
{
    dosomething();
}

, Jon Skeet.

0
source

Using the Jon Skeet solution above, I added a fix if the start time starts at the beginning of the time. For example, you start work after 6:00 p.m. and finish it the next morning at 5 a.m. then you need to check it out and apply another day to the end. I hope this helps, I personally spent too much time on this work. have a great day :)

if (stopHour < startHour)
{
end = today.AddHours(stopHour+24);
}

Full code below.

private static bool IsInRunHours()
{
        try
        {
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
            // after = 18 before = 5

            // Only take the current time once; otherwise you could get into a mess if it
            // changes day between samples.
            DateTime now = DateTime.Now;
            DateTime today = now.Date;

           Int32 startHour = ConfigurationManager.AppSettings["UpdateRunAfter"].ToInt();
            Int32 stopHour = ConfigurationManager.AppSettings["UpdateRunBefore"].ToInt(); 


            DateTime start = today.AddHours(startHour);
            DateTime end = today.AddHours(stopHour);

            if (stopHour < startHour)
            {
                 end = today.AddHours(stopHour+24);

            }


            //ConfigurationManager.AppSettings["UpdateRunBefore"].ToInt()
            //ConfigurationManager.AppSettings["UpdateRunAfter"].ToInt()
            // Cope with a start hour later than an end hour - we just
            // want to invert the normal result.
            bool invertResult = end < start;

            // Now check for the current time within the time period
            bool inRange = (start <= now && now <= end) ^ invertResult;
            if (inRange)
            {
                return true;
            }
            else
            {
                return false;
            }



        }
        catch
        {
            return false;
        }

    }
0
source

Source: https://habr.com/ru/post/1782665/


All Articles