code_junkie

How to determine the last business day in a given month?

Nov 12th, 2011
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. var holidays = new List<DateTime>{/* list of observed holidays */};
  2. DateTime lastBusinessDay = new DateTime();
  3. var i = DateTime.DaysInMonth(month, year);
  4. while (i > 0)
  5. {
  6. var dtCurrent = new DateTime(year, month, i);
  7. if(dtCurrent.DayofWeek < DayOfWeek.Saturday && dtCurrent.DayOfWeek >Sunday &&
  8. !holidays.Contains(dtCurrent))
  9. {
  10. lastBusinessDay = dtCurrent;
  11. i = 0;
  12. }
  13. else
  14. {
  15. i = i.AddDays(-1);
  16. }
  17. }
  18.  
  19. Function GetLastBusinessDay(ByVal Year As Integer, ByVal Month As Integer) As DateTime
  20. Dim LastOfMonth As DateTime
  21. Dim LastBusinessDay As DateTime
  22.  
  23. LastOfMonth = New DateTime(Year, Month, DateTime.DaysInMonth(Year, Month))
  24.  
  25. If LastOfMonth.DayOfWeek = DayOfWeek.Sunday Then
  26. LastBusinessDay = LastOfMonth.AddDays(-2)
  27. ElseIf LastOfMonth.DayOfWeek = DayOfWeek.Saturday Then
  28. LastBusinessDay = LastOfMonth.AddDays(-1)
  29. Else
  30. LastBusinessDay = LastOfMonth
  31. End If
  32.  
  33. Return LastBusinessDay
  34.  
  35. End Function
  36.  
  37. Day day = getLastDayOfMonth
  38. int days = getDaysInMonth
  39. for i = days to 0
  40. if day is weekday
  41. if day is not holiday
  42. return day
  43. end if
  44. end if
  45. day = prevDay
  46. days--
  47. end for
  48.  
  49. throw exception because no business day was found in the month
  50.  
  51. Function GetLastDay(ByVal month As Int32, ByVal year As Int32) As Date
  52. Dim D As New Date(year, month, Date.DaysInMonth(year, month))
  53. For i As Integer = 0 To Date.DaysInMonth(year, month)
  54. Select Case D.AddDays(-i).DayOfWeek
  55. Case DayOfWeek.Saturday, DayOfWeek.Sunday 'Not a weekday
  56. Case Else 'Is a weekday. Flag as first weekday found
  57. Return D.AddDays(-i)
  58. 'you can add other code here which could also do a check for holidays or ther stuff since you have a proper date value to look at in the loop
  59. End Select
  60. Next
  61. End Function
Add Comment
Please, Sign In to add comment