-2

im having problem setting the time of aftternoon login that should be 12:31pm to 4:59pm

When i try to exucute the afternoon login where i change the time it gives me not recorded the else statement

DateTime date = DateTime.Now;

// 0:00 to 11:59
if (date.Hour >= 0 && date.Hour <= 11) {
    MessageBox.Show("Morning Login");
}
// 12:00 between 0 minutes and 30
else if (date.Hour == 12 && date.Minute >= 0 && date.Minute <= 30) {
    MessageBox.Show("Morning Logout");
}
// This is the condition I'm having problems with
else if (date.Hour == 12 || date.Hour >= 13 && date.Hour <= 16) {
    // I'm setting the time to afternoon login that should be 12:31pm to 4:59pm
    MessageBox.Show("Afternoon Login");
}
else if (date.Hour >= 17 && date.Hour <= 23)
{
    MessageBox.Show("Afternoon Logout");
}
else
{
    MessageBox.Show("Not recorded");
}
IndieGameDev
  • 2,820
  • 3
  • 11
  • 28
newbie
  • 1
  • 3
  • What is `date.Hour`'s value? `date.Minute`? – mjwills Sep 09 '20 at 06:14
  • `else if (date.Hour == 12 || date.Hour >= 13 && date.Hour <= 16` would be simpler as `else if (date.Hour >= 12 && date.Hour <= 16` (with the bonus that you don't need to consider order of operations - https://docs.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=vs-2019). – mjwills Sep 09 '20 at 06:14
  • `date.Hour == 12 && date.Minute >= 0 && date.Minute <= 30` would be simpler as `date.Hour == 12 && date.Minute <= 30`. – mjwills Sep 09 '20 at 06:15
  • Additionally to other comments, do note this condition `date.Minute >= 0` makes no sense, minutes would never have a negative value. – Cleptus Sep 09 '20 at 06:18
  • This could be simplified a lot if `DateTime.TimeOfDay` was compared against specific `TimeSpan` values instead of checking hour and minute separately – Panagiotis Kanavos Sep 09 '20 at 06:19

1 Answers1

0

As Panagiotis suggested in the comments, You should use TimeSpan for comparison

And your condition for the afternoon check can be

else if ((date.TimeOfDay >= new TimeSpan(12, 31, 0)) && (date.TimeOfDay <= new TimeSpan(16, 59, 0)))
{
   MessageBox.Show("Afternoon Login");
}

Refer this

Mihir Dave
  • 3,954
  • 1
  • 11
  • 26