DateDiff "ww" in .NET

InertiaM

Well-known member
Joined
Nov 3, 2007
Messages
663
Location
Kent, UK
Programming Experience
10+
In VB6, I used to use
VB.NET:
DateDiff("ww", DateSerial(Year(Now), 4, 5), Now)

What's the VB.NET logic equivalent? I've tried

VB.NET:
Convert.ToInt32(Math.Floor((Date.Now - New Date(Date.Now.Year, 4, 5)).TotalDays / 7) + 1)

but it gives different answers :confused:

VB.NET:
        Dim dtDateToCheck As Date
        Dim iFW_VB6 As Integer = 0
        Dim iFW_VBdotNET As Integer = 0
        For i As Integer = -5 To 100 'days backward to days forward to check
            dtDateToCheck = Date.Now.AddDays(i)

            iFW_VB6 = Convert.ToInt32(Microsoft.VisualBasic.DateDiff("ww", New Date(dtDateToCheck.Year, 4, 5), dtDateToCheck))
            iFW_VBdotNET = Convert.ToInt32(Math.Floor((Date.Now - New Date(Date.Now.Year, 4, 5)).TotalDays / 7) + 1)

            If iFW_VB6 <> iFW_VBdotNET Then
                MessageBox.Show(dtDateToCheck.ToString & Environment.NewLine & iFW_VB6.ToString & " does not agree with " & iFW_VBdotNET.ToString)
                Exit Sub
            End If
        Next

        MessageBox.Show("All values match!")
 
CInt((date2-date1).TotalDays/7) is correct.
 
VB.NET:
        Dim dtDateToCheck As Date
        Dim iFW_VB6 As Integer = 0
        Dim iFW_VBdotNET As Integer = 0
        For i As Integer = 0 To 100 'days backward to days forward to check
            dtDateToCheck = Date.Now.AddDays(i)
            iFW_VB6 = Convert.ToInt32(Microsoft.VisualBasic.DateDiff("ww", New Date(dtDateToCheck.Year, 4, 5), dtDateToCheck))
            iFW_VBdotNET = CInt((dtDateToCheck - New Date(dtDateToCheck.Year, 4, 5)).TotalDays / 7)
            If iFW_VB6 <> iFW_VBdotNET Then
                MessageBox.Show(dtDateToCheck.ToString & Environment.NewLine & iFW_VB6.ToString & " does not agree with " & iFW_VBdotNET.ToString)
                Exit Sub
            End If
        Next

        MessageBox.Show("OK")
        Exit Sub

gives a messagebox with

VB.NET:
27/04/2008 13:14:49
4 does not agree with 3
 
DateDiff is wrong then, unless you want a different behaviour than CInt(Double).
 
Uhh.. Doesnt Convert.ToInt32 and CInt behave differnetly? I seem to recall reading that one of them rounds and one of them floors?!
 
The nearest I can get to is

VB.NET:
    Private Function FinancialWeek(ByVal DateToCheck As Date) As Integer
        If (DateToCheck - New Date(DateToCheck.Year, 4, 5)).TotalDays > 0 Then
            Return Math.Floor((Math.Floor((DateToCheck - New Date(DateToCheck.Year, 4, 5)).TotalDays) - 1) / 7) + 1
        Else
            Return Math.Floor((Math.Floor((DateToCheck - New Date(DateToCheck.Year - 1, 4, 5)).TotalDays) - 1) / 7) + 1
        End If
    End Function

This appears to be fine for any value within this financial year, but not for any value outside it.

Oh well, maybe there are some things legacy VB functions are still good at ;)
 
Back
Top