Is there a nice concise way to write this logic in C#?
if ((DateTime.Now >= "8:00 AM") && (DateTime.Now < 5:00 PM))
{// do something}
I am making a demo app where I want to make something happen in the work day, but I don’t want this code to stand out much (a lot of casting = bad). (Because I want my demo stuff to be easier to see.
Well, you could do:
Note that I generally prefer to only use the
DateTime.Nowproperty once, copying the result into the local variable as above – that way you don’t get odd possibilities due to the time changing between calls. Not a problem here, but it could be in other cases.Another possibility is to use
DateTime.TimeOfDayif you want to handle things that way. I think the above is about as simple as it gets though.EDIT: Steven pointed out that I changed the && in your original logic to || – your original logic can never work, as it can never be before 8am and after 5pm. The above works for “if it’s not in the working day” – if you want “if it is in the working day” you just need: