C# 如何检查 DateTime.Now 是否仅在时间部分的两个给定日期时间之间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12998739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:16:24  来源:igfitidea点击:

How to check if DateTime.Now is between two given DateTimes for time part only?

c#wpfwindows-phone

提问by Niels

For my app I need to know if Now()is between two values.

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

The user can set a start- and an end-time so he will not disturbed by a notification (during the night for example).

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

So if have got two TimePickers (start- and end-time) that the user can set.

因此,如果有两个TimePicker用户可以设置的 s(开始时间和结束时间)。

Lets say the user sets 22:00for the StartTimeand 07:00for the EndTime(this would cover the night).

假设用户设置22:00StartTime07:00EndTime(这将涵盖夜晚)。

How can I check if the DateTime.Nowis between the selected Start and End time?

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

EDIT:I only want this to work with the Hour and minutes part. So if the user sets the Start and End time this should work for every night.

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

采纳答案by Gabe

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:

首先,您需要将所有内容转换为相同的单位(我们将使用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);

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

回答by Paul Fleming

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;

Update 08-Jun-2016
Not sure why the downvote was appropriate as this is a working solution. The OP did ask specifically for DateTime, however I do recommend using TimeSpaninstead as per the answer by @Gabe.

2016 年 6 月 8 日更新
不知道为什么downvote 是合适的,因为这是一个有效的解决方案。OP 确实特别要求DateTime,但是我建议TimeSpan按照@Gabe 的回答使用。

Here's a working function as per my answer:

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

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

Here's a working fiddle: https://dotnetfiddle.net/vZCXqv.

这是一个工作小提琴:https: //dotnetfiddle.net/vZCXqv

Full code:

完整代码:

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

回答by Stan

Dupe of Find if current time falls in a time range

Dupe of Find 当前时间是否在一个时间范围内

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, again, taken from dupe.

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

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
}

回答by iefpw

Just do straight comparison.

直接比较就行了。

if(date > startdate && date < enddate)

if(date > startdate && date < enddate)

回答by yhw42

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 Nowinto TimeSpans:

由于您只聚会两次没有日期,因此您需要弄清楚这两次是否来自同一天。如果你把StartTimeEndTimeNowTimeSpans

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

回答by Rohit Sachan

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

回答by Suplanus

I use this, so you can pass DateTime directly:

我使用这个,所以你可以直接传递 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);
    }