Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate date in for loop?

Tags:

c#

for-loop

I have some values.

 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)

I want to run the shift for 6 days. but after each 2 days Shift id 1 rotate to shift id 2 and again after two days shift id 2 rotate to shift id 1 and so on... My output should be like

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

I am getting shift id through a foreach loop. I tried like below mentioned way but not getting a proper resul. Please help me solve this issue

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

I am stucked with this from last day, anybody help me . No need of consider my for loop, kindly provide a for loop which generate the above mentioned output

like image 651
Mohan Lal Avatar asked Mar 04 '15 05:03

Mohan Lal


2 Answers

You can try this,

     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);
     }
like image 55
Mahesh Avatar answered Oct 04 '22 20:10

Mahesh


Don't use dates at loop cycle, use abstract indicies. You can really abstract from concrete numbers and use only variables for managing result. So you can easily change rotationDays count and even workshifts labels array without changing cycle.

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]);
        }
like image 32
Vladimir Mezentsev Avatar answered Oct 04 '22 21:10

Vladimir Mezentsev