简体   繁体   English

如何根据C#中的星期几确定当前时间是否在重复发生的时间范围内?

[英]How can I determine if the current time is within a reoccurring time range based on the day of week in C#?

Not sure how to approach this. 不知道如何解决这个问题。 I have an app where users can select a time range (say 5:00 PM to 10:00 AM) that repeats daily based on the days selected by the user (say Mon, Thurs, and Sat). 我有一个应用程序,用户可以在其中选择一个时间范围(例如5:00 PM到10:00 AM),该时间范围会根据用户选择的日期(例如周一,周四和周六)每天重复一次。 How can I determine if the current time is within one of these ranges? 如何确定当前时间是否在这些范围之一内?

Edit: 编辑:

I took a look at Find if current time falls in a time range , but I don't think this is a duplicate because it doesn't address the issue I am getting confused on. 我看了一下“ 查找当前时间是否在某个时间范围内” ,但是我认为这不是重复的,因为它不能解决我感到困惑的问题。 For example, I'm not sure what to do when a time range falls into the next day. 例如,我不确定当时间范围落到第二天该怎么办。 Like in my example, how would I handle 5:00 PM to 10:00 AM the next day ? 就像我的示例一样,我将如何处理第二天的 5:00 PM至10:00 AM? What about when it falls into the next week like from Sat to Sun (which would be 6 to 0)? 下一个星期,如从星期六到星期日(6到0),该怎么办?

More Info: 更多信息:

I am not working with DateTime objects, I am working with the DaysOfWeek enum and and Timespans to represent the time. 我没有使用DateTime对象,我正在使用DaysOfWeek枚举和Timespans来表示时间。 Below is a representation of the ranges I would be working with: 以下是我将使用的范围的表示:

| startDay | startTime | endDay |  endTime  |
|----------|-----------|--------|-----------|
|    1     | 17:00:00  |   2    | 09:00:00  |
|    3     | 09:00:00  |   3    | 17:00:00  |
|    6     | 17:00:00  |   0    | 09:00:00  |

Assuming a Sunday start-of-week: 假设星期日是星期几:

var now = DateTime.Now;

// offset from "Sunday"
var i = now.Date.AddDays(-(double) now.DayOfWeek);
// normalize to this week
var s = i.AddDays((double) startDay).AddHours(startTime.TotalHours);
// normalize to this week
var e = i.AddDays((double)((endDay < startDay) ? endDay + 7 : endDay)).AddHours(endTime.TotalHours);
Debug.Assert(now >= s && now <= e);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM