-3

I am working on a project that involves shift work so I need my shifts to display correctly as time moves along. I currently have 3 shifts (shifth = start shifthe = end) as follows. Shift1 8AM-4PM Shift2 4:01PM-12:01AM and Shift3 12:02AM-7:59AM the AM times are overriding my PM times as I am in military time so they never change it just stays at shift3. any help would be greatly appreciated below is my code.

 private void shifts_Tick(object sender, EventArgs e)
    {


      if (DateTime.Now.TimeOfDay >= new TimeSpan(Settings.Default.shift1h,Settings.Default.shift1m, 0) && DateTime.Now.TimeOfDay <= new TimeSpan(Settings.Default.shift1he, Settings.Default.shift1me, 0))
        {
            txtbxname1.Text = "Shift1";
        }

           if (DateTime.Now.TimeOfDay >= new TimeSpan(Settings.Default.shift2h, Settings.Default.shift2m, 0)  && DateTime.Now.TimeOfDay <= new TimeSpan(Settings.Default.shift2he, Settings.Default.shift2me, 0))
          {
              txtbxname1.Text = "Shift2";
          }
         if (DateTime.Now.TimeOfDay >= new TimeSpan(Settings.Default.shift3h, Settings.Default.shift3m, 0) && DateTime.Now.TimeOfDay <= new TimeSpan(Settings.Default.shift3he, Settings.Default.shift3me, 0))
          {
              txtbxname1.Text = "Shift3";
          }
    }
Marcus
  • 97
  • 1
  • 11

2 Answers2

0

If you use if...else if ... else there will be no problem

if (DateTime.Now.TimeOfDay >= ...... first shift selection logic ....)
{
    txtbxname1.Text = "Shift1";
}
else if (DateTime.Now.TimeOfDay >= ....second shift selection logic...)        
{
    txtbxname1.Text = "Shift2";
}
else // everything else is the third shift
{
    txtbxname1.Text = "Shift3";
}
Steve
  • 213,761
  • 22
  • 232
  • 286
0

The simplest thing would be to take current TimeSpan from the midnight, take minutes and compare them to the benchmark values like (I've calculated the value only for the third shift):

var minutes = (DateTime.Now - DateTime.Today).TotalMinutes;
if (minutes < 2)
    txtbxname1.Text = "Shift2";
else if (minutes < thirdShiftMinutesValue)
    txtbxname1.Text = "Shift3";
else if (minutes < firstShiftMinutesValue)
    txtbxname1.Text = "Shift1";
else
    txtbxname1.Text = "Shift2";
Ivan Ičin
  • 9,672
  • 5
  • 36
  • 57