offset for weekend days using mod - vb.net

I have a .NET console app that needs to run on the 1st, 5th, 10th, 15th, 20th, and 25th of each month. Depending on which date it runs, the app sends out a different type of email. I want to adjust the app so that if one of those dates is on the weekend, it runs the following Monday.
I believe this does what I want:
Dim adjustedDay As Integer = Day(Today)
If Today.ToString("ddd") = "Mon" And adjustedDay > 1 Then
If adjustedDay Mod 5 = 1 Then
adjustedDay -= 1
ElseIf adjustedDay Mod 5 = 2 Then
adjustedDay -= 2
End If
End If
Select Case adjustedDay
Case 1
...
Case 5
...
Case ...
...
End Select
So if today is Monday, 9/21/2015, I adjust to "20" and run that code. If Monday happens to land on the 1st, I don't adjust it.
is there a cleaner way to do this?

Your code won't work correctly if Monday falls on the 2nd or 3rd of the month. (ie. 2 mod 5 = 2, so adjustedDay = 0)
The other tricky part is that the app needs to run on the 1st, but 1 mod 5 = 1 which is different to all the other cases where it is 0.
Something like this should work:
'Returns 0 for non-email days, otherwise returns 1,5,10,15,20,25
Private Function GetEmailDay(ByVal currentDate as Date) As Integer
If currentDate.DayOfWeek = DayOfWeek.Saturday OrElse
currentDate.DayOfWeek = DayOfWeek.Sunday Then
Return 0
End If
Dim day As Integer = currentDate.Day
Dim emailDays As New List(Of Integer)( {1,5,10,15,20,25} )
If emailDays.Contains(day) Then
Return day
End If
If currentDate.DayOfWeek = DayOfWeek.Monday Then
If emailDays.Contains(day-1) Then 'check Sunday
Return day-1
End If
If emailDays.Contains(day-2) Then 'check Saturday
Return day-2
End If
End If
Return 0
End Function

Related

DayOfWeek - get day number

I have this method:
Dim dayofweek As Integer = CInt(DateTime.Now.DayOfWeek)
Dim startdayvalue As Integer = 0
Select Case args(1).ToLower
Case "monday"
startdayvalue = 1
Case "tuesday"
startdayvalue = 2
Case "wednesday"
startdayvalue = 3
Case "thursday"
startdayvalue = 4
Case "friday"
startdayvalue = 5
Case "saturday"
startdayvalue = 6
Case "sunday"
startdayvalue = 7
End Select
Return (dayofweek - startdayvalue + 7) Mod 7 + 1
args(1) is the a day like "monday" to "sunday" which the user can throw in. I want it to always start with value 1 for the given regional settings. I guess something is wrong with my last line because it gives me the wrong values. For example it gives me Monday = 1 (correct) Tuesday = 7 (incorrect) Sunday (2). In my regional settings week starts with Monday and should be one and Sunday 7.
You shouldn't try to work against the abstraction the .NET Framework supplies.
You can obtain the generic DayOfWeek number from your given culture:
Dim ci As System.Globalization.CultureInfo
ci = New System.Globalization.CultureInfo("de-DE")
Dim fdow As System.DayOfWeek
fdow = ci.DateTimeFormat.FirstDayOfWeek
You can use this DayOfWeek to compare against your DateTime.DayOfWeek to identify if this date is on the first day of the week for your culture.

Getting Dates of Current week does not work as expected

iam trying to get the Dates (Monday - Sunday) for the current Week.
This is my current Code:
Dim kw As Integer = DatePart(DateInterval.WeekOfYear, Now, , FirstWeekOfYear.FirstFourDays)
If DatePart(DateInterval.Weekday, Now, Microsoft.VisualBasic.FirstDayOfWeek.Sunday) = 6 Then
kw = kw + 1
End If
Dim CurrDateFirstDay As Date = DateAdd(DateInterval.Day, 1, ReturnDateForWeekNumber(kw))
For i = 1 To 7
strCurrDay = FormatDateTime(CurrDateFirstDay, DateFormat.LongDate)
........
My Problem is that my code starts at 16.01.2013 and the last date is Thuesday 22.01.2013 next week. Why is that? Why does he start Wednesday 16.01.2013 and not Monday 14.01.2013? And why do i get returned dates of the next week? What iam doing wrong?
Edit:
ReturnDateForWeekNumber:
Public Shared Function ReturnDateForWeekNumber(ByVal iWeek As Integer) As DateTime
Return DateAdd(DateInterval.WeekOfYear, iWeek - 1, FirstDayOfYear)
End Function
What am I doing wrong?
You should step through your code in the debugger and observe the result, as I did:
Dim kw As Integer = DatePart(DateInterval.WeekOfYear, Now, , FirstWeekOfYear.FirstFourDays)
This returns the current week, which is week 3.
If DatePart(DateInterval.Weekday, Now, Microsoft.VisualBasic.FirstDayOfWeek.Sunday) = 6 Then
kw = kw + 1
End If
This checks if the weekday is the 6th day of the week (friday). We're not friday so If condition is not entered.
Dim CurrDateFirstDay As Date = DateAdd(DateInterval.Day, 1, ReturnDateForWeekNumber(kw))
This adds one day to the result of ReturnDateForWeekNumber, which returns:
Return DateAdd(DateInterval.WeekOfYear, iWeek - 1, FirstDayOfYear)
This adds 2 (week 3 minus 1) weeks to the first day of the year (Jan 1st), a tuesday. Jan 1st + 2 weeks = January 15th.
Now remember that you add one day to ReturnDateForWeekNumber, that's why CurrDateFirstDay has a value of January 16th.
Edit
I think your code is overly complicated and uses a lot of legacy VB6 functions. I would do it this way:
Dim myDate As Date = DateTime.Today
Dim dayDiff As Integer = myDate.DayOfWeek - DayOfWeek.Monday
Dim currentDay As Date = myDate.AddDays(-dayDiff) 'Monday
For i = 1 to 7
Console.WriteLine(currentDay)
'Do something with current day
currentDay = currentDay.AddDays(1)
Next
You might have to do some adjustments for your case but I believe this approach is simpler and less error prone.
Dim dateStartDateOfWeek As Date = GetWeekStartDate(52, 2014)
Dim dateEndDateOfWeek As Date = DateAdd(DateInterval.Day, 7, dateStartDateOfWeek)
Private Function GetWeekStartDate(ByVal weekNumber As Integer, ByVal year As Integer) As Date
Dim startDate As New DateTime(year, 1, 1)
Dim weekDate As DateTime = DateAdd(DateInterval.WeekOfYear, weekNumber - 1, startDate)
Return DateAdd(DateInterval.Day, (-weekDate.DayOfWeek) + 1, weekDate)
End Function

VB.NET - counting days between two dates with exclusions

I'm trying to count the days between two dates, excluding Saturdays and Sundays. I've written this code so far
Dim startDay As Integer
Dim endDay As Integer
Dim days As Integer
Dim count As Integer
startDay = dtpStartDate.Value.DayOfWeek
endDay = dtpEndDate.Value.DayOfWeek
For days = startDay To endDay
If days = 0 Or days = 6 Then 'Sunday = 0, Saturday = 6
count += 1
End If
Next
lblNoOfDays.Text = count
It works fine if you choose the two dates within the same week. (ex: 23rd Jan to 27th Jan, gives the result 5)
But if I set them to dates in different weeks, (ex : 23rd Jan to 30th Jan, gives the result 1), it gives incorrect results.
I know it happens because of the loop but I can't think of a way to overcome this. Can anyone give me a suggestion, solution??
Thank you
Dim count = 0
Dim totalDays = (dtpEndDate - dtpStartDate).Days
For i = 0 To totalDays
Dim weekday As DayOfWeek = startDate.AddDays(i).DayOfWeek
If weekday <> DayOfWeek.Saturday AndAlso weekday <> DayOfWeek.Sunday Then
count += 1
End If
Next
lblNoOfDays.Text = count
This function calculates the non-weekend days between two dates:
Public Shared Function WorkingDaysElapsed(ByVal pFromDate As Date, ByVal pToDate As Date) As Integer
Dim _elapsedDays As Integer = 0
Dim _weekendDays As DayOfWeek() = {DayOfWeek.Saturday, DayOfWeek.Sunday}
For i = 0 To (pToDate - pFromDate).Days
If Not _weekendDays.Contains(pFromDate.AddDays(i).DayOfWeek) Then _elapsedDays += 1
Next
Return _elapsedDays
End Function

subtract if the day of the week is a saturday or sunday

if the subtracted date is a saturday or sunday then subtract more days, before adding to arraylist
when i do this, the date stays the same and doesnt subtract, i get a conversion string to double error
Dim aftersubtraction As Date
Dim fromatafter As Date
aftersubtraction = departuredate.AddDays(-dates1.Text)
fromatafter = aftersubtraction.AddDays(-gracep.Text)
If fromatafter.DayOfWeek = "Saturday" Then
fromatafter.AddDays(-1)
dates.Add(fromatafter.ToString("MM/dd/yyyy"))
ElseIf fromatafter.DayOfWeek = "Sunday" Then
fromatafter.AddDays(-2)
dates.Add(fromatafter.ToString("MM/dd/yyyy"))
Else
dates.Add(fromatafter.ToString("MM/dd/yyyy"))
End If
While fromatafter.DayOfWeek = DayOfWeek.Saturday OrElse fromatafter.DayOfWeek = DayOfWeek.Sunday
fromatafter = fromatafter.AddDays(-1)
End While
dates.Add(fromatafter.ToString("MM/dd/yyyy"))
You have to assigne the date returned from AddDays to your variable.
And please set option strict and explicit. Why?
if im not mistaken the vb dayofweek function returns an integer and not a string.
' 0 = Sunday
' 1 = Monday
' 2 = Tuesday
' 3 = Wednesday
' 4 = Thursday
' 5 = Friday
' 6 = Saturday
hence the error message.
your getting the string to double error on the
line with the if statement... becase .dayofweek does not return a string... it returns an integer... so an integer is never going to be = "Saturday" or "Sunday"... its going to be equal to 0 or 1

calculate date add, but only weekdays

I would like to calculate a new date simply by using the build-in dateadd function, but take into account that only weekdays should be counted (or 'business days' so to speak).
I have come up with this simple algorithm, which does not bother about holidays and such. I have tested this with some simple dates, but would like some input if this can be done in better ways.
This sample assumes a week with 5 business days, monday-friday, where first day of the week is monday. Dateformatting used here is d-m-yyyy, the sample calculates with a startdate of october 1, 2009.
Here is the simple form:
Dim d_StartDate As DateTime = "1-10-2009"
Dim i_NumberOfDays As Integer = 12
Dim i_CalculateNumberOfDays As Integer
If i_NumberOfDays > (5 - d_StartDate.DayOfWeek) Then
i_CalculateNumberOfDays = i_NumberOfDays
Else
i_CalculateNumberOfDays = i_NumberOfDays + (Int(((i_NumberOfDays + (7 - d_StartDate.DayOfWeek)) / 5)) * 2)
End If
MsgBox(DateAdd(DateInterval.Day, i_CalculateNumberOfDays, d_StartDate))
Which I try to explain with the following piece of code:
''' create variables to begin with
Dim d_StartDate as Date = "1-10-2009"
Dim i_NumberOfDays as Integer = 5
''' create var to store number of days to calculate with
Dim i_AddNumberOfDays as Integer
''' check if amount of businessdays to add exceeds the
''' amount of businessdays left in the week of the startdate
If i_NumberOfDays > (5 - d_StartDate.DayOfWeek) Then
''' start by substracting days in week with the current day,
''' to calculate the remainder of days left in the current week
i_AddNumberOfDays = 7 - d_StartDate.DayOfWeek
''' add the remainder of days in this week to the total
''' number of days we have to add to the date
i_AddNumberOfDays += i_NumberOfDays
''' divide by 5, because we need to know how many
''' business weeks we are dealing with
i_AddNumberOfDays = i_AddNumberOfDays / 5
''' multiply the integer of current business weeks by 2
''' those are the amount of days in the weekends we have
''' to add to the total
i_AddNumberOfDays = Int(i_AddNumberOfDays) * 2
''' add the number of days to the weekend days
i_AddNumberOfDays += i_NumberOfDays
Else
''' there are enough businessdays left in this week
''' to add the given amount of days
i_AddNumberOfDays = i_NumberOfDays
End If
''' this is the numberof dates to calculate with in DateAdd
dim d_CalculatedDate as Date
d_CalculatedDate = DateAdd(DateInterval.Day, i_AddNumberOfDays, d_StartDate)
Thanks in advance for your comments and input on this.
I used the .DayOfWeek function to check if it was a weekend. This does not include holiday implementation. It has been tested. I realize this question is old but the accepted answer didn't work. However, I did like how clean it was so I thought I'd update it and post. I did change the logic in the while loop.
Function AddBusinessDays(startDate As Date, numberOfDays As Integer) As Date
Dim newDate As Date = startDate
While numberOfDays > 0
newDate = newDate.AddDays(1)
If newDate.DayOfWeek() > 0 AndAlso newDate.DayOfWeek() < 6 Then '1-5 is Mon-Fri
numberOfDays -= 1
End If
End While
Return newDate
End Function
Public Shared Function AddBusinessDays(ByVal startDate As DateTime, _
ByVal businessDays As Integer) As DateTime
Dim di As Integer
Dim calendarDays As Integer
'''di: shift to Friday. If it's Sat or Sun don't shift'
di = (businessDays - Math.Max(0, (5 - startDate.DayOfWeek)))
''' Start = Friday -> add di/5 weeks -> end = Friday'
''' -> if the the remaining (<5 days) is > 0: add it + 2 days (Sat+Sun)'
''' -> shift back to initial day'
calendarDays = ((((di / 5) * 7) _
+ IIf(((di Mod 5) <> 0), (2 + (di Mod 5)), 0)) _
+ (5 - startDate.DayOfWeek))
Return startDate.AddDays(CDbl(calendarDays))
End Function
Your plan seems like it should work. Make sure you wrap it in a function instead of doing out the calculations every place you use it so that if/when you discover you need to account for holidays, you don't have to change it in tons of places.
The best way I can think of for implementing support for holidays would be to add days one at a time in a loop. Each iteration, check if its a weekend or a holiday, and if it is add another day and continue (to skip it). Below is an example in pseudocode (I don't know VB); no guarantees its correct. Of course, you need to provide your own implementations for isWeekend() and isHoliday().
function addBusinessDays(startDate, numDays)
{
Date newDate = startDate;
while (numDays > 0)
{
newDate.addDays(1);
if (newDate.isWeekend() || newDate.isHoliday())
continue;
numDays -= 1;
}
return newDate;
}
My first thought for the holiday thing was to simply look up the number of holidays between the start date and the end date and add that to your calculation, but of course this won't work because the end date is dependent on the number of holidays in that interval. I think an iterative solution is the best you'll get for holidays.
I'm using this code to calculate the date:
dayOfWeek = startDate.DayOfWeek
weekendDays = 2 * Math.Floor((dayOfWeek + businessDays - 0.1) / 5)
newDate = startDate.AddDays(businessDays + weekendDays)
The second line computes the number of full weekends that we have to add and then multiplies them by 2 to obtain the number of days.
The additional -0.1 constant is used to avoid adding days if (dayOfWeek + businessDays) is multiple of 5, and final date is friday.
Private Function AddBusinessDays(ByVal dtStartDate As DateTime, ByVal intVal As Integer) As DateTime
Dim dtTemp As DateTime = dtStartDate
dtTemp = dtStartDate.AddDays(intVal)
Select Case dtTemp.DayOfWeek
Case 0, 6
dtTemp = dtTemp.AddDays(2)
End Select
AddBusinessDays = dtTemp
End Function
please check this code for adding working days
Dim strDate As Date = DateTime.Now.Date
Dim afterAddDays As Date
Dim strResultDate As String
Dim n As Integer = 0
For i = 1 To 15
afterAddDays = strDate.AddDays(i)
If afterAddDays.DayOfWeek = DayOfWeek.Saturday Or afterAddDays.DayOfWeek = DayOfWeek.Sunday Then
n = n + 1
End If
Next
strResultDate = afterAddDays.AddDays(n).ToShortDateString()
Private Function AddXWorkingDays(noOfWorkingDaysToAdd As Integer) As Date
AddXWorkingDays = DateAdd(DateInterval.Weekday, noOfWorkingDaysToAdd + 2, Date.Today)
If Weekday(Today) + noOfWorkingDaysToAdd < 6 Then AddXWorkingDays = DateAdd(DateInterval.Weekday, 2, Date.Today)
End Function
One approach would be to iterate from the start date and add or subtract one day with each iteration if the date is not a Saturday or Sunday. If zero is passed as iAddDays then the function will return dDate even if that date is a Saturday or Sunday. You could play around with the logic to get the outcome you are looking for if that scenario is a possibility.
Public Function DateAddWeekDaysOnly(ByVal dDate As DateTime, ByVal iAddDays As Int32) As DateTime
If iAddDays <> 0 Then
Dim iIncrement As Int32 = If(iAddDays > 0, 1, -1)
Dim iCounter As Int32
Do
dDate = dDate.AddDays(iIncrement)
If dDate.DayOfWeek <> DayOfWeek.Saturday AndAlso dDate.DayOfWeek <> DayOfWeek.Sunday Then iCounter += iIncrement
Loop Until iCounter = iAddDays
End If
Return dDate
End Function
Easy way
function addWerktage($date,$tage){
for($t=0;$t<$tage;$t++){
$date = $date + (60*60*24);
if(date("w",$date) == 0 || date("w",$date) == 6){ $t--; }
}
return $date;
}
This produces the same result as the accepted answer, including starting on weekends, while handling negative offsets and without looping. It's written in c# but should work in any enviroment where numeric weekdays start at Sunday and end at Saturday, and where integer division rounds to 0.
public static DateTime AddWeekdays(DateTime date, int offset)
{
if (offset == 0)
{
return date;
}
// Used to calculate the number of weekend days skipped over
int weekends;
if (offset > 0)
{
if (date.DayOfWeek == DayOfWeek.Saturday)
{
// Monday is 1 weekday away, so it will take an extra day to reach the next weekend
int daysSinceMonday = -1;
// Add two weekends for every five days
int normalWeekends = (offset + daysSinceMonday) / 5 * 2;
// Add one for this Sunday
int partialWeekend = 1;
weekends = normalWeekends + partialWeekend;
}
else
{
// It will take this many fewer days to reach the next weekend.
// Note that this works for Sunday as well (offset -1, same as above)
int daysSinceMonday = date.DayOfWeek - DayOfWeek.Monday;
// Add two weekends for every five days (1 business week)
weekends = (offset + daysSinceMonday) / 5 * 2;
}
}
else
{
// Same as the positive offset case, but counting backwards.
// daysSinceFriday will be 0 or negative, except for Saturday, which is +1
int daysSinceFriday = date.DayOfWeek - DayOfWeek.Friday;
weekends = date.DayOfWeek == DayOfWeek.Sunday
? (offset + 1) / 5 * 2 - 1
: (offset + daysSinceFriday) / 5 * 2;
}
return date.AddDays(offset + weekends);
}
Since the pattern of 2 extra days per 5 days repeats after a full week, you can effectively exhaustively test it:
private static DateTime AddWeekdaysLooping(DateTime date, int offset)
{
DateTime newDate = date;
int step = Math.Sign(offset);
while (offset != 0)
{
newDate = newDate.AddDays(step);
if (newDate.DayOfWeek != DayOfWeek.Sunday && newDate.DayOfWeek != DayOfWeek.Saturday)
{
offset -= step;
}
}
return newDate;
}
void TestWeekdays()
{
DateTime initial = new DateTime(2001, 1, 1);
for (int day = 0; day < 7; day += 1)
{
for (int offset = -25; offset <= 25; offset += 1)
{
DateTime start = initial.AddDays(day);
DateTime expected = AddWeekdaysLooping(start, offset);
DateTime actual = AddWeekdays(start, offset);
if (expected != actual) {
throw new Exception($"{start.DayOfWeek} + {offset}: expected {expected:d}, but got {actual:d}");
}
}
}
}
Dim result As Date
result = DateAdd("d", 2, Today)
If result.DayOfWeek = DayOfWeek.Saturday Then
result = DateAdd("d", 2, result)
MsgBox(result)
ElseIf result.DayOfWeek = DayOfWeek.Sunday Then
result = DateAdd("d", 1, result)
MsgBox(result)
ElseIf result.DayOfWeek = DayOfWeek.Monday Then
MsgBox(result)
ElseIf result.DayOfWeek = DayOfWeek.Tuesday Then
MsgBox(result)
ElseIf result.DayOfWeek = DayOfWeek.Wednesday Then
MsgBox(result)
ElseIf result.DayOfWeek = DayOfWeek.Thursday Then
MsgBox(result)
ElseIf result.DayOfWeek = DayOfWeek.Friday Then
MsgBox(result)
End If