如何在for循环中迭代日期?

时间:2015-03-04 05:58:12

标签: c# for-loop

我有一些价值观。

 DateTime date=04/03/2015(date)
 Total Woring days=6 (total)
 Rotation Days=2 (rotationday)
 Shift Group=S1(this group contain two shift id 1 and 2)

我想要轮班6天。但是每隔2天后,移位id 1旋转以移动id 2并在两天后再次移动id 2旋转以移动id 1,依此类推...... 我的输出应该像

04/03/2015=1
05/03/2015=1
06/03/2015=2
07/03/2015=2
08/03/2015=1
09/03/2015=1

我通过foreach循环获得shift id。我尝试了下面提到的方式但没有得到适当的结果。请帮我解决这个问题

SqlCommand cmd2 = new SqlCommand("select ShiftID from ShiftGroup  where  
ShiftName='" + ide + "'", conn2);
SqlDataAdapter sda2 = new SqlDataAdapter(cmd2);
DataSet ds4 = new DataSet();
var rows2 = ds4.Tables[0].Rows;
if (ds4.Tables[0].Rows.Count > 0)
{
foreach (DataRow row2 in rows2)
{
string shiftname = Convert.ToString(row2["ShiftID"]);
DateTime date=04/03/2015(date)
Total Woring days=6 (total)
Rotation Days=2 (rotationday)
DateTime rotation= date.AddDays(rotationday);//
DateTime totaldate = date.AddDays(workingdays);
for (DateTime rotation = date; rotation <= totaldate; rotation = rotation.AddDays(1))//total working days 
{
    //to check rotation date
if (rotation <= totaldate )
{
allocation.shiftallocation( rotation, shiftid);
}
}
}

从最后一天开始我就被这个问题所困扰,任何人都帮助我。不需要考虑我的for循环,请提供一个生成上述输出的for循环

5 个答案:

答案 0 :(得分:3)

你可以试试这个,

     DateTime date=DateTime.ParseExact("04/03/2015","dd/MM/yyyy",CultureInfo.InvariantCulture);
    DateTime totaldate = date.AddDays(6);
    for (int i=0; date <= totaldate; date = date.AddDays(1),i++)//total working days 
     {

         if((i/2)%2==0)
              Console.WriteLine(date+" "+1);
         else
              Console.WriteLine(date+" "+2);
     }

答案 1 :(得分:1)

var date = DateTime.Parse("04/03/2015");

var totalWorkingDays = 6;
var rotationDays = 2;

var rotationId = 1;
var rotationCounter = 1;

for (DateTime rotation = date; 
     rotation <= date.AddDays(totalWorkingDays); 
     rotation = rotation.AddDays(1))
{
    Console.WriteLine(rotation + " " + rotationId);

    if (rotationCounter++ == 2)
    {
        rotationCounter = 1;
        rotationId = 3 - rotationId;
    }
}

或者,使用linq查询

var date = DateTime.Parse("04/03/2015");

var totalWorkingDays = 6;
var rotationDays = 2;

foreach (var d in Enumerable.Range(0, totalWorkingDays)
               .Select((i, index) => date.AddDays(i) + 
                   (((int)(index / rotationDays)) % 2 == 1 ? " 2" : " 1")))
{
    Console.WriteLine(d);
}

答案 2 :(得分:1)

不要在循环周期中使用日期,使用抽象的指示。您可以从具体数字中抽象出来,并仅使用变量来管理结果。因此,您可以轻松更改rotationDays计数,甚至可以更改标签数组,而无需更改周期。

var date = DateTime.Parse("04/03/2015");

        var totalWorkingDays = 15;
        var rotationDays = 2;

        var workshifts = new[] { "S1", "S2" };
        var currentWorkshiftIndex = 0;
        for (int dayIndex = 0; dayIndex <= totalWorkingDays; dayIndex++) {
            if (dayIndex != 0 && dayIndex % rotationDays == 0) currentWorkshiftIndex = (currentWorkshiftIndex + 1) % workshifts.Length;
            Console.WriteLine(date.AddDays(dayIndex) + " " + workshifts[currentWorkshiftIndex]);
        }

答案 3 :(得分:1)

考虑到假期的通用解决方案。

int totalDays = 10;
int rotationDays = 3;
int[] shifts = new[] { 1, 2 };
string startDate = "04/03/2015";
var holidays = new List<DayOfWeek>(new[] { DayOfWeek.Saturday, DayOfWeek.Sunday, DayOfWeek.Tuesday });
var shiftAllocations = new Dictionary<DateTime, int>();
int currentShiftIndex = 0;

DateTime current = DateTime.ParseExact(startDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

for (int i = 0; i < totalDays; i += rotationDays)
{
    var currentShiftId = shifts[currentShiftIndex];

    // For each day from the current day till the number of shift rotation days, allocate the shift.
    for (int j = 0; j < rotationDays;)
    {
        // If the current day is a holiday, move to the next day by incrementing i.
        if (holidays.Contains(current.AddDays(i + j).DayOfWeek))
        {
            i++;                        
            continue;
        }

        shiftAllocations.Add(current.AddDays(i + j), currentShiftId);
        j++;
    }

    // Increase the shift index if the value is within the bounds. If not reset the index to the beginning
    if ((currentShiftIndex + 1) >= shifts.Length)
        currentShiftIndex = 0;
    else
        currentShiftIndex++;
}

foreach (var kvp in shiftAllocations)
{
    Console.WriteLine(kvp.Key.ToString("dd/MM/yyyy") + ":" + kvp.Value);
}

答案 4 :(得分:1)

根据你对每周5个工作日的评论,我写了这个:

  var start = new DateTime(2015, 04, 03);
  var working_day_count = 6;
  var rotation_interval = 2;
  var shifts = new List<int> { 1, 2 };

  var rotation_count = 1;
  var shift_index = 0;

  for (var i = 0; i < working_day_count; i++) {
    while ((start.DayOfWeek == DayOfWeek.Saturday) || 
      (start.DayOfWeek == DayOfWeek.Sunday)) {
      start = start.AddDays(1);
    }

    Console.WriteLine(start.ToString() + " = " + shifts[shift_index].ToString());

    start = start.AddDays(1);

    rotation_count++;
    if (rotation_count > rotation_interval) {
      rotation_count = 1;
      shift_index++;
      if (shift_index >= shifts.Count) {
        shift_index = 0;
      }
    }
  }

只需根据需要更改前四个varibales的值即可。 我试图让它易于理解而不是高性能或紧凑。