Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

Can someone help me getting accurate dateDiff between two dates?
I need to get how many years between two dates.



Dim firstDate As Date
Dim SecondDate As Date
firstDate = "2016-09-28"
SecondDate = Now



TextBox1.Text = DateDiff(DateInterval.Year, firstDate, SecondDate)
'The textbox value = 1 .. it should be Zero because between September 28 2016 to Date today is not equivalent to 1 whole year.

i just cant divide it by 365 or 366.

another example is.
Datediff(dateInterval.year, 2015-02-01 , 2017-01-01 ) = 2 .
it should be 1 only. unless the present date is 2017-02-01.

Please help.

What I have tried:

Dim firstDate As Date
Dim SecondDate As Date
        firstDate = "2016-09-28"
        SecondDate = Now


       
        TextBox1.Text = DateDiff(DateInterval.Year, firstDate, SecondDate)
Posted
Updated 26-Jan-17 2:46am
Comments
[no name] 23-Jan-17 9:04am    
See https://www.codeproject.com/Tips/569948/Working-with-Age-its-not-the-same-as-a-timespan

Check this out:
Imports System
Public Module Module1
    Public Sub Main()
		
		Dim firstdate As New Date(2015, 2, 1, 0, 0, 0)
		Dim seconddate As New Date(2017, 1, 1, 0, 0, 0)
		
		Dim timespan As TimeSpan = seconddate - firstdate
		Dim interval As DateTime = DateTime.MinValue.AddDays(timespan.Days)

		Console.WriteLine("{0} - {1} = {2} years", seconddate, firstdate, interval.Year  - 1)
    End Sub
End Module
Reference: TimeSpan Structure (System)[^]
 
Share this answer
 
Thank you Peter.

That is helpful.
I also have may own solution i want to share. This gives accurate result.

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim x As Integer
        Dim dt1 As Date
        Dim dt2 As Date

        dt1 = DateTimePicker1.Text
        dt2 = DateTimePicker2.Text
        dt1 = dt1.AddYears(x)
        x = DateDiff(DateInterval.Year, dt1, dt2)
        dt1 = dt1.AddYears(x)

        If dt1 <= dt2 Then
            x = x
            TextBox1.Text = x
        Else
            x = x - 1
            TextBox1.Text = x
        End If
    End Sub


End Class
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900