Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorten a DateTime condition check

if ((DateTime.Now.DayOfWeek != DayOfWeek.Friday && DateTime.Now.DayOfWeek != DayOfWeek.Saturday) &&
((DateTime.Now.Hour >= 10 && DateTime.Now.Hour < 13) || (DateTime.Now.Hour >= 20 && DateTime.Now.Hour < 23)))

I have to shorten this condition, any suggestions?

like image 535
Sinros Avatar asked Dec 08 '22 14:12

Sinros


2 Answers

You could change the hours to use

(DateTime.Now.Hour % 12) +1 >= 10 && (DateTime.Now.Hour % 12) +1 < 13

Maybe even without the second check.

I don't think you can improve much more than that than looking for other methods like other answers

Update I tested the above and its wrong, but this is more sadistic and works

var check = (DateTime.Now.Hours - 10 % 12) % 10;
 var checkV = (DateTime.Now.Hours >= 10 && check < 3);

Test Code

for (int i = 0; i < 24; i++)
{
    var check = (i - 10 % 12) % 10;
    bool checkV = (i >= 10 && check < 3);
    Console.WriteLine(i.ToString() + ": " + checkV.ToString());
 }
 Console.ReadKey();

Update 2 Complete shortened code

if(   (int)DateTime.Now.DayOfWeek < 5 && 
           DateTime.Now.Hours >= 10 && 
         ((DateTime.Now.Hours - 10 % 12) % 10) < 3)
like image 185
Sayse Avatar answered Dec 11 '22 09:12

Sayse


Well, you could build an extension method:

public static bool BoundsCheck(this DateTime d, int min, int max, int min2, int max2)
{
    return (d.DayOfWeek != DayOfWeek.Friday &&
        d.DayOfWeek != DayOfWeek.Saturday &&
        d.Hour >= min &&
        d.Hour < max) ||
        (d.Hour >= min2 && d.Hour < max2);
}

and then call it like this:

if (DateTime.Now.BoundsCheck(10, 13, 20, 23))...
like image 27
Mike Perrenoud Avatar answered Dec 11 '22 09:12

Mike Perrenoud