Calculate days of month - vb.net

Is there any method for calculating the number of days in a month?

Yes:
Const July As Integer = 7
Const Feb As Integer = 2
' daysInJuly gets 31. '
Dim daysInJuly As Integer = System.DateTime.DaysInMonth(2001, July)
' daysInFeb gets 28 because the year 1998 was not a leap year. '
Dim daysInFeb As Integer = System.DateTime.DaysInMonth(1998, Feb)
' daysInFebLeap gets 29 because the year 1996 was a leap year. '
Dim daysInFebLeap As Integer = System.DateTime.DaysInMonth(1996, Feb)
Credit goes to MSDN.

http://authors.aspalliance.com/aspxtreme/sys/DateTimeClassDaysInMonth.aspx
Public Shared Function DaysInMonth ( _
ByVal year As Integer, _
ByVal month As Integer _
} As Integer

Dim d As New DateTime(2010, 4, 1)
Dim month As Integer = d.Month
While d.Month = month
Console.WriteLine(d.[Date])
d = d.AddDays(1)
End While
You can of course change how you output the Date to format it to your will.

To get the number of days of current month
Dim CurrentMonthDays As Int16 = DateTime.DaysInMonth(DateTime.Now.Year,DateTime.Now.Month)

Use an array: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Add one to Feb if (year mod 400 = 0) or ( (year mod 4 = 0) and not (year mod 100 = 0) )

You have two simple solutions:
5546>>m&1|30^(m==2)*2+(m==2&&y%4==0)))
or
(62648012>>m*2&3)+28+(m==2&&y%4==0)))
where m is the number of month and y is the year.
this solution is the same below, an array, but the array is bit masked in magic numbers.

Related

How many Fridays are there in the month ?. Visual Basic .NET

I want help writing a code to calculate the number of Fridays in a particular month, for example January or February .... etc.
You could use such an iterator method:
Public Iterator Function GetWeekDaysInMonth(year As Int32, month As Int32, dayOfWeek As DayOfWeek) As IEnumerable(Of Date)
Dim day = New Date(year, month, 1)
Dim diff As Int32 = (7 + (day.DayOfWeek - dayOfWeek)) Mod 7
day = day.AddDays(-1 * diff)
If day.Month <> month Then day = day.AddDays(7)
While day.Month = month
Yield day
day = day.AddDays(7)
End While
End Function
Usage:
Dim countFridaysYanuary = GetWeekDaysInMonth(2022, 1, DayOfWeek.Friday).Count()
Dim countFridaysFebruary = GetWeekDaysInMonth(2022, 2, DayOfWeek.Friday).Count()
If you want them all in a list, use:
Dim fridaysInYanuary = GetWeekDaysInMonth(2022, 1, DayOfWeek.Friday).ToList()
If you just want the first:
Dim firstFridayInJanuary = GetWeekDaysInMonth(2022, 1, DayOfWeek.Friday).First()
If you want to output all fridays of the year 2022 per month, you can use:
For i As Int32 = 1 To 12
Dim fridays = GetWeekDaysInMonth(2022, i, DayOfWeek.Friday)
Console.WriteLine(String.Join(", ", fridays.Select(Function(d) d.ToShortDateString())))
Next
Demo: https://dotnetfiddle.net/2ptUlX

VBA calculate the school year from the date of birth and current year - Except when the calendar year changes from December to January

Hope someone can help with this. I have an access 2010 DB. I want to calculate the current school year for a pupil. To do this I have the date of birth on the form and a blank bound text box called "NCY"
The following doesn't take into account when the year changes from December to January, it changes the school year when I don't want it to change it until September (School year runs September to August)
Private Sub yearGroup_GotFocus()
Dim nowDate As Date
Dim dob As Date
Dim dobMonth As Integer
Dim dobYear As Integer
Dim NCY As Integer
nowDate = Date
nowYear = year(nowDate)
dob = Me.dateOfBirth
dobMonth = Month(dob)
dobYear = year(dob)
NCY = nowYear - dobYear
If dobMonth > 8 Then
Me.yearGroup.Value = NCY - 6
Else
Me.yearGroup.Value = NCY - 5
End If
End Sub
In English I want something along the lines of;
If the current month of current year is >8 then increase the NCY by 1
unless the current year has changed by 1 and the month in that year is <9
Hope this makes sense.
Thank you in advance
I hardcoded the DOB on this one because I was practicing in Excel. This assumes the ch8ild is in grade 1 when he is 6 years old before August. Mostly in the USA we start Kindergarten at age five, and grade 1 at age 6. You can adjust accordingly.
Private Sub yearGroup_GotFocus2()
Dim nowDate As Date
Dim dob As Date
Dim dobMonth As Integer
Dim dobYear As Integer
Dim NCY As Integer
Dim currentlyInSchool As Boolean
Dim schoolYear As Long
Dim schoolGrade As Long
nowDate = Date
nowYear = Year(nowDate)
dob = DateValue("Feb 15, 2000")
dobMonth = Month(dob)
dobYear = Year(dob)
NCY = nowYear - dobYear
abc = 123
' First find out the current school year.
' School year runs from August to May
If Month(nowDate) <= 5 Then
schoolYear = Year(nowDate) - 1
Else
schoolYear = Year(nowDate)
End If
Debug.Print "School year: " & schoolYear & "/" & Mid(CStr(schoolYear + 1), 3, 2)
If Month(dob) < 8 Then
schoolGrade = 1
Else
schoolGrade = 0
End If
schoolGrade = schoolGrade + (schoolYear - (Year(dob) + 5))
Debug.Print "Pupil Grade: " & schoolGrade
End Sub

Special date formatted string to Date (VB.net)

If i have a string containing a date formatted like this:
1402-3
which means Year: 2014, Week: 02 and Day number 3 (monday is 1), how can i convert this to a normal date? (in this case the date above is today; 2014-01-08 - wednesday 8 jan 2014)
Edit: I came up with a function like this, can anyone tell if this is gonna fail or maybe have a better and better coded function/solution?
Private Function StrangeFormattedDateToRegularDate(ByVal StrangeDate As String) As Date
Dim Y As String = "20" & StrangeDate.Substring(0, 2) 'I'll be dead before this fails, haters gonna hate
Dim W As String = StrangeDate.Substring(2, 2)
Dim D As String = StrangeDate.Substring(5, 1)
'Get first day of this year
Dim RefDate As Date = New Date(CInt(Y), 1, 1)
'Get the first day of this week (can be the year before)
Dim daysOffSet As Integer = DayOfWeek.Monday - RefDate.DayOfWeek
RefDate = RefDate.AddDays(daysOffSet)
'Add as many days as the weeks is
RefDate = RefDate.AddDays(7 * CInt(W))
'now the date is the last day of this week (plus one day), remove the days that are ahead, and remove that extra day
Dim daysToRemove = ((7 - CInt(D)) * -1) - 1
RefDate = RefDate.AddDays(daysToRemove)
Return RefDate
End Function
This should be what you're looking for :) This looked challenging so I tried it. Tell me if it works for you or not :)
Function GetDate(InputDate As String) As DateTime
Dim FirstDayofYear As Date = CType("1/1/20" & Mid(InputDate, 1, 2), Date)
Dim LastDayofYear As Date = CType("12/31/20" & Mid(InputDate, 1, 2), Date)
Dim target As Date
For x = 0 To DateDiff(DateInterval.Day, FirstDayofYear, LastDayofYear)
Dim dfi = DateTimeFormatInfo.CurrentInfo
Dim calendar = dfi.Calendar
Dim weekOfyear = calendar.GetWeekOfYear(FirstDayofYear.AddDays(x), dfi.CalendarWeekRule, DayOfWeek.Sunday)
If CInt(Mid(InputDate, 3, 2)) = weekOfyear And CInt(Mid(InputDate, InStr(InputDate, "-") + 1)) = FirstDayofYear.AddDays(x).DayOfWeek Then
target = FirstDayofYear.AddDays(x)
GoTo skip
End If
Next x
skip:
Return target
End Function
This works up to Year 2099. We're probably all dead by then.

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