-4

So I'm trying to figure out if a DateTime is between two Dates as well as two times.

For example,

if DateTime.Now >= January && DateTime.Now < August && DateTime.Now >= 9am && DateTime.Now < 12pm
     //do something

I'm not really sure how to go about this, any help is appreciated :')

Hannah
  • 25
  • 1
  • 3
  • 1
    Side recommendation, you should assign `DateTime.Now` to a variable and use that variable in all of your calculations, so that the same value is being used in all parts of the comparison. Otherwise, the value of `DateTime.Now` could be inconsistent throughout your conditional. – Joe Sewell Mar 24 '20 at 22:24
  • Unless `January` and `August` are variable names, the value on the right side of each comparison is not a `DateTime`. You need to construct a `DateTime` against which to compare `DateTime.Now`. Have you tried anything beyond those arbitrary literals? – Lance U. Matthews Mar 24 '20 at 22:27

2 Answers2

-1
if (DateTime.Now.Month < 8 && DateTime.Now.Hour >= 9 && DateTime.Now.Hour < 12) {
 // do your thing
}
-1

From the documentation at https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.8#properties:

if (DateTime.Now.Month >= 1 && DateTime.Now.Month < 8
    && DateTime.Now.Hour >= 9  && DateTime.Now.Hour < 12)

where DateTime.Month is a number between 1 and 12, and DateTime.Hour is a number between 0 and 23.

José Pedro
  • 1,097
  • 3
  • 14
  • 24