简体   繁体   English

C#的强制性DateTime问题-确定UtcNow是否仅在给定的时间跨度之间

[英]Obligatory DateTime issues with C# - Determine if UtcNow is between given time span only

I have a situation in which I need to set up a re-occuring time span (for this example, 6 PM - 6 AM is the span of time) 我遇到需要重新设置时间跨度的情况(对于此示例,时间跨度为6 PM-6 AM)

Date is not relevent to this. 日期与此无关。 It is presumed to be a check every single day. 假定它每天都是支票。

I am having trouble wrapping my head around how to do it because using DateTime.UtcNow does yield me the right time, but it does not yield the right day. 我很难解决该问题,因为使用DateTime.UtcNow确实可以给我合适的时间,但是却不能满足我的要求。 However using DateTime.MinValue does not yield the current time. 但是,使用DateTime.MinValue不会产生当前时间。 And I was not able to set the Date manually. 而且我无法手动设置日期。 I have explored the other posts on stack overflow, and I'm just misunderstanding something, I think.. but this is my paltry code at the moment... 我浏览了堆栈溢出的其他文章,我只是误解了一些,..但是这是我目前的微不足道的代码...

var start = DateTime.MinValue.Date.Add(new TimeSpan(18, 0, 0));
            var end = DateTime.MinValue.Date.Add(new TimeSpan(6, 0, 0));
            var timezone = TimeZone.CurrentTimeZone.GetUtcOffset(start);
            var now = DateTime.UtcNow;
            now.Date = DateTime.MinValue;

            // is right now greater than 6pm est?
            Console.WriteLine(start.TimeOfDay < now);
            Console.WriteLine(end < DateTime.UtcNow);
            Console.WriteLine(start.ToShortTimeString());
            Console.WriteLine(DateTime.UtcNow.TimeOfDay);
            Console.WriteLine(timezone.ToString());

            Console.ReadLine();

I am not sure as what you want to achieve but for a check won't something like this do for you 我不确定您想要达到的目标,但是对于支票来说,这样的事情不会对您有所帮助

DateTime dt3 = DateTime.UtcNow;
if(dt3.Hour <= 6 || dt3.Hour >=18)//24 hr format
   MessageBox.Show("6PM - 6AM range");// UTC will have only one time and should get satisfied irrespective of date

To check if it is between midnight UTC and 6AM UTC or between 6PM UTC and midnight UTC the following day, you're going to have to combine two clauses: 要检查第二天是在午夜UTC和6AM UTC之间还是在下午6点UTC和午夜UTC之间,您将必须结合两个子句:

bool IsNowInTimeSpan = (DateTime.UtcNow >= DateTime.Date && DateTime.UtcNow <= DateTime.Date.AddHours(6)) ||
                       (DateTime.UtcNow >= DateTime.Date.AddHours(18) && DateTime.UtcNow <= DateTime.Date.AddDays(1));

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

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