Timespan AM到PM c#

时间:2017-06-24 20:20:46

标签: c# timespan

我正在开展一项涉及轮班工作的项目,所以随着时间的推移,我需要轮班正确显示。我目前有3个班次(shifth = start shifthe = end)如下。 Shift1 8 AM-4PM Shift2 4:01 PM-12:01 AM和Shift3 12:02 AM-7:59 AM AM时间超过我的PM时间,因为我在军事时间,所以他们永远不会改变它只是停留在shift3。我的代码将在下面提供任何帮助。

 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";
          }
    }

2 个答案:

答案 0 :(得分:0)

如果您使用if ... else if ... else将没有问题

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";
}

答案 1 :(得分:0)

最简单的方法是从午夜开始使用当前的TimeSpan,花几分钟时间将它们与基准值进行比较,例如(我只计算了第三班的值):

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";