help with datetime

johnfrench

New member
Joined
Aug 14, 2007
Messages
2
Programming Experience
1-3
Hello all,

I want to be able to have a formula that calculates how many fridays in a given month, or how many monday, tuesday, wednesday, thursdays in a given month.

i know i can do something like this...

For eachdate = StartDate To EndDate

Select Case WeekDay(eachdate, vbMonday)
Case 5
GetFriCount = GetFriCount + 1
End Select

Next eachdate

but i wonder if there is a more elegant solution using the datetime functions...

any ideas anyone?

thanks!
 
Try this:
VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
    CountDayOfWeek(New Date(2007, 11, 1), New Date(2007, 11, 30))
End Sub

Sub CountDayOfWeek(ByVal fromDate As Date, ByVal toDate As Date)
    Dim ht As New Hashtable
    Dim d As Date = fromDate
    Do While d <= toDate
        If ht.ContainsKey(d.DayOfWeek) Then
            ht(d.DayOfWeek) += 1
        Else
            ht.Add(d.DayOfWeek, 1)
        End If
        d = d.AddDays(1)
    Loop

    Dim sb As New System.Text.StringBuilder
    For Each entry As DictionaryEntry In ht
        sb.AppendFormat("{0} {1}s" & vbNewLine, entry.Value, entry.Key)
    Next
    MsgBox(sb.ToString)
End Sub
It was written with .Net 2.0 but for your .Net 1.1 platform, hopefully it runs too. For .Net 2.0 I would have used a Dictionary(Of DayOfWeek, Integer) instead of the Hashtable.
 
Dim DaysOfWeek As New Dictionary(Of DayOfWeek, Integer)
then same code, then
For Each entry As KeyValuePair(Of DayOfWeek, Integer) In DaysOfWeek
and same
 
i can't get this example(above) working with a dictionary.
could you rewrite it using a dictionary?(please)
 
like I said, only those two code line where changed:
VB.NET:
Sub CountDayOfWeek(ByVal fromDate As Date, ByVal toDate As Date)
    Dim theCounter As New Dictionary(Of DayOfWeek, Integer)
    Dim d As Date = fromDate
    Do While d <= toDate
        If theCounter.ContainsKey(d.DayOfWeek) Then
            theCounter(d.DayOfWeek) += 1
        Else
            theCounter.Add(d.DayOfWeek, 1)
        End If
        d = d.AddDays(1)
    Loop

    Dim sb As New System.Text.StringBuilder
    For Each entry As KeyValuePair(Of DayOfWeek, Integer) In theCounter
        sb.AppendFormat("{0} {1}s" & vbNewLine, entry.Value, entry.Key)
    Next
    MsgBox(sb.ToString)
End Sub
 
Back
Top