如何检查DateTime.Now是否仅在时间部分两个给定的DateTimes之间? [英] How to check if DateTime.Now is between two given DateTimes for time part only?

查看:66
本文介绍了如何检查DateTime.Now是否仅在时间部分两个给定的DateTimes之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

因此,如果有两个 TimePicker (开始时间和结束时间)。

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

可以说用户设置了 StartTime 为22:00 07:00 > EndTime (这将覆盖整个夜晚)。

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

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

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

编辑:
我只希望此功能与小时一起使用和分钟部分。因此,如果用户设置了开始时间和结束时间,那么它应该每晚都可以使用。

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.

推荐答案

首先,您需要将所有内容转换为相同的单位(我们将使用 TimeSpan ),那么您需要查看开始时间是否超过午夜,最后根据检查结果进行比较:

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

您会这样称呼:

bool silenceAlarm = TimeBetween(DateTime.Now, StartTime.Value, EndTime.Value);

这篇关于如何检查DateTime.Now是否仅在时间部分两个给定的DateTimes之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆