Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 确定时间是否在指定的小时范围内_C# - Fatal编程技术网

C# 确定时间是否在指定的小时范围内

C# 确定时间是否在指定的小时范围内,c#,C#,我是C#的新手。我想检查一个时间是否在给定的2小时之间,如果是这样,那么做一些事情。谁能给我举个例子吗 伪代码示例: int starthour = 17; int endhour = 2; if ( hour between starthour and endhour){ dosomething(); } 如何检查hour是否介于starthour和endhour之间?在C#中,时间以AM/PM格式返回,因此我不知道它是否会将17数字理解为“5 PM”。当减去DateTimes时,

我是C#的新手。我想检查一个时间是否在给定的2小时之间,如果是这样,那么做一些事情。谁能给我举个例子吗

伪代码示例:

int starthour = 17;
int endhour = 2;

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

如何检查
hour
是否介于
starthour
endhour
之间?在C#中,时间以AM/PM格式返回,因此我不知道它是否会将
17
数字理解为“5 PM”。

当减去
DateTime
s时,您会得到一个结构,可以查询总小时数(属性):


如果您想查看时间是否相同,那么可以使用-对于相同的
DateTime
s,它将等于0。

假设您谈论的是当前时间,我会这样做:

// 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();
}
//只取当前时间一次;否则你可能会陷入混乱,如果它
//样本之间的日期变化。
DateTime now=DateTime.now;
DateTime今天=现在。日期;
DateTime开始=今天.AddHours(startHour);
DateTime end=today.AddHours(endHour);
//应对比结束时间晚一个小时的开始-我们只是
//要反转正常结果。
bool invertResult=结束<开始;
//现在检查时间段内的当前时间
bool inRange=(开始<代码>bool CheckHour(日期时间检查,日期时间开始,日期时间结束)
{
如果(检查.TimeOfDayend.TimeOfDay)
返回false;
其他的
返回true;
}
int starthour=17;
int endhour=2;
int nowhour=DateTime.Now.Hour;
如果(结束小时<开始小时)
{
endhour+=24;
小时+=24;
}

如果(starthour事实上,如果我们在这里处理纯小时,就像一个从0到23再到0的阿贝尔环,我相信下面是一个有效的解决方案:

(开始-结束)

现在,除非我弄错了,开始吧≰ 由于开始时间是下午5点第1天,而现在是凌晨1点第1天,这是在现在之前,因此测试失败,但原始问题希望凌晨1点包含在范围内,因为凌晨1点在下午5点到凌晨2点之间。我错过了什么吗

@布莱恩

另外,看看你的代码,我认为你可以检测凌晨1点,但现在你可能会遇到晚上10点(22:00)的问题,因为你的时间变成:

  • 起点是17
  • 终点是26
  • 现在是22+24=46!因此您将在小于测试中失败

显然,一般情况下是非常棘手的!当你像我一样局限于谷歌电子表格时,情况更是如此。

如果你想像我一样比较分钟数,你可以使用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;
        }
//立即初始化、睡眠开始和睡眠结束日历
Calendar now=Calendar.getInstance();
Calendar sleepStart=Calendar.getInstance();
Calendar sleepEnd=Calendar.getInstance();
//将开始和结束日历分配给用户指定的星号和结束时间
long startSleep=settings.getLong(“startTime”,0);
long-endSleep=settings.getLong(“endTime”,0);
sleepStart.setTimeInMillis(startSleep);
sleepEnd.setTimeInMillis(endSleep);
//从时间中提取小时和分钟
int endHour=sleepEnd.get(日历.HOUR/天);
int startHour=sleepStart.get(日历小时);
int nowhoor=now.get(日历.HOUR/OF\u日);
int endMinute=sleepEnd.get(Calendar.MINUTE);
int startMinute=sleepStart.get(Calendar.MINUTE);
int nowMinute=now.get(Calendar.MINUTE);
//把我们的时间都安排在几分钟内
int endTime=(endHour*60)+endMinute;
int startTime=(startHour*60)+startMinute;
int nowTime=(nowthour*60)+nowtimin;
/*****************是什么让这100%有效***************************/
//测试结束时间是否为第二天
如果(结束时间<开始时间){
if(nowTime>0&&nowTime布尔值范围=(startTime使用上面Jon Skeet的解决方案,我添加了一个修正,如果开始时间在开始时间之后,例如晚上6点后开始工作,第二天早上5点结束。然后你需要检查这个问题,并将另一天应用到结束时间。希望有帮助,我个人在这项工作上花费了太多时间。祝你有一个美好的一天:)

if(停止小时<开始小时)
{
结束=今天。添加小时数(停止小时数+24);
}
完整代码如下

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;
        }

    }
private static bool IsInRunHours()
{
尝试
{
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“应用设置”);
//之后=18之前=5
//只使用当前时间一次;否则,如果使用当前时间,您可能会陷入混乱
//样本之间的日期变化。
DateTime now=DateTime.now;
DateTime今天=现在。日期;
Int32 startHour=ConfigurationManager.AppSettings[“UpdateRunAfter”].ToInt();
Int32 stopHour=ConfigurationManager.AppSettings[“UpdateRunBefore”].ToInt();
DateTime开始=今天.AddHours(startHour);
DateTime end=today.AddHours(stopHour);
如果(停止小时<开始小时)
{
结束=今天。添加小时数(停止小时数+24);
}
//ConfigurationManager.AppSettings[“UpdateRunBefore”].ToInt()
//ConfigurationManager.AppSettings[“UpdateRunAfter”].ToInt()
//应对比结束时间晚一个小时的开始-我们只是
//要反转正常结果。
bool invertResult=结束<开始;
//现在检查时间段内的当前时间

bool inRange=(开始你所说的“两次之间的小时数是真的”是什么意思?在什么意义上是真的?@hunter,我相信我们想要的
int starthour = 17;
int endhour = 2;
int nowhour = DateTime.Now.Hour;

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

if (starthour <= nowhour && nowhour <= endhour)
{
    dosomething();
}
        //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;
        }
if (stopHour < startHour)
{
end = today.AddHours(stopHour+24);
}
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;
        }

    }