利用时间检查它是否在周五至周日之间并忽略

时间:2016-01-10 23:14:37

标签: c#

我正在检查当前时间并忽略它是否在星期五下午3点到星期天晚上7点之后。代码有效,但有更简单的方法吗?

        Boolean iCheck = true;
        DateTime iCurTime = DateTime.Now;

        //if its friday and 3pm or after don't check
        if (iCurTime.ToString("ddd") == "Fri") {
            if (iCurTime.TimeOfDay >= new TimeSpan(15, 0, 0)) {
                iCheck = false;
            }
        }

        //if its saturday dont check
        if (iCurTime.ToString("ddd") == "Sat") {
            iCheck = false;
        }

        //if its sunday and less than 7pm dont check
        if (iCurTime.ToString("ddd") == "Sun") {
            if (iCurTime.TimeOfDay <= new TimeSpan(19, 0, 0)) {
                iCheck = false;
            }
        }

2 个答案:

答案 0 :(得分:1)

我喜欢LINQ ......

        var dtl = new List<DateTime>();
        dtl.Add(DateTime.Now);
        var DaysOfWeekToInclude = dtl.Where(
            d => d.DayOfWeek == DayOfWeek.Friday || 
            d.DayOfWeek != DayOfWeek.Saturday || 
            d.DayOfWeek == DayOfWeek.Sunday);

        var FirstFilter = DaysOfWeekToInclude.Where(
            p => 
            p.DayOfWeek == DayOfWeek.Friday && p.Hour <= 15);

        var SecondFilter = FirstFilter.Where(
            p => p.DayOfWeek == DayOfWeek.Sunday && p.Hour > 19);
        var filtered = SecondFilter.First();

答案 1 :(得分:1)

不确定这是否比您的解决方案更好,但它可以正常工作

//use Sunday_Monday midnight as reference
            TimeSpan friday_3PM = new TimeSpan(4, 15, 0, 0); 
            TimeSpan sunday_7PM = new TimeSpan(6, 19, 0, 0); 

            DateTime now = DateTime.Now;
            TimeSpan timeSpan = now - now.AddDays(-1 * (((int)now.DayOfWeek + 6) % 7)).Date;
            if((timeSpan < friday_3PM) || (timeSpan > sunday_7PM))
            {
            }