4

I'm trying to convert this VB block to C#.

  Public Function AddWorkingDays(ByVal DateIn As DateTime, _
   ByVal ShiftDate As Integer) As DateTime
    Dim b As Integer

    Dim datDate As DateTime = DateIn ' Adds the [ShiftDate] number of working days to DateIn'
    For b = 1 To ShiftDate
        datDate = datDate.AddDays(1)
        ' Loop around until we get the need non-weekend day'
        If Weekday(datDate) = 7 Then
            datDate = datDate.AddDays(2)
        End If
    Next
    Return datDate
End Function

So far I've got

public DateTime AddWorkingDays(DateTime DateIn, int ShiftDate)
{
    int b = 0;

    DateTime datDate = DateIn;
    // Adds the [ShiftDate] number of working days to DateIn
    for (b = 1; b <= ShiftDate; b++)
    {
        datDate = datDate.AddDays(1);
        // Loop around until we get the need non-weekend day
        if (DateAndTime.Weekday(datDate) == 7)
        {
            datDate = datDate.AddDays(2);
        }
    }
    return datDate;
}

I know that there doesn't exist in C# DateAndTime I just put it in the if statement to complete the block of code. My real problem is getting the IF statement to work. I am not sure if DateTime.Now.Weekday is the same statement as in the previous VB code.

George Johnston
  • 31,652
  • 27
  • 127
  • 172
barkl3y
  • 179
  • 1
  • 2
  • 7
  • http://stackoverflow.com/questions/400421/equivalent-of-weekday-function-of-vb6-in-c-sharp – NamedJohnny Apr 18 '13 at 16:11
  • Thanks NamedJohnny but I looked at that question before posting and didn't understand it. – barkl3y Apr 18 '13 at 16:14
  • The answers you have so far will work, but keep in mind (for more complex issues) that you can always use the Microsoft.VisualBasic assembly from C#. It's especially useful for its financial library. – Dave Doknjas Apr 18 '13 at 16:17
  • 1
    Aside: (Counts for both VB and C#) declare the loop variable *inside the loop* and not before. In C#, don’t iterate from 1 to the end of the range +1; instead, iterate from 0 to the end of the range. In other words: `for (int b = 0; b < ShiftDate; b++)`. This is idiomatic and expected; everything else requires an explanation and trips readers of the code up. – Konrad Rudolph Apr 18 '13 at 17:35
  • Thanks Konrad I didn't write the original VB code (a previous intern did) and missed that, I've since made the correction. – barkl3y Apr 18 '13 at 17:38

2 Answers2

7

Just use the DayOfWeek enumeration, e.g.

datDate.DayOfWeek == DayOfWeek.Saturday
George Johnston
  • 31,652
  • 27
  • 127
  • 172
6

Weekday returns 7 for Saturday, so you can use DateTime.DayOfWeek property and compare it to DayOfWeek.Saturday:

    if (datDate.DayOfWeek == DayOfWeek.Saturday)
    {
        datDate = datDate.AddDays(2);
    }
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263