Function to get accurate years between two Gregorian dates (1 Viewer)

Accessna

Registered User.
Local time
Today, 10:57
Joined
Oct 4, 2015
Messages
15
Code:
Function GetYears(ByVal DateFm As Long, ByVal DateTo As Long) As Double
  Dim Leap004 As Long
  Dim Leap100 As Long
  Dim Leap400 As Long
  Dim LeapYears As Long
  Dim SmblYears As Long
  Dim Leap As Long
  Dim Smbl As Long
  Dim LeapFm As Long
  Dim SmblFm As Long
  Dim inDate As Long
  Dim yy As Integer
  
  'Years between 102 And 9999
  If DateFm < DateSerial(102, 1, 1) Or _
     DateTo < DateSerial(102, 1, 1) Then Exit Function
  
  If DateFm > DateTo Then
    inDate = DateFm
    DateFm = DateTo
    DateTo = inDate
  End If
  '------------------
  DateFm = DateFm - 1
  '------------------
  inDate = DateFm
  GoSub Calculate
  LeapFm = Leap
  SmblFm = Smbl
  '------------------
  inDate = DateTo
  GoSub Calculate
  Leap = Leap - LeapFm
  Smbl = Smbl - SmblFm
  '------------------
  GetYears = (Leap / 366) + (Smbl / 365)
  Exit Function
  '------------------
Calculate:
  yy = Year(inDate) - 1
  
  Leap004 = Fix(yy / 4)
  Leap100 = Fix(yy / 100)
  Leap400 = Fix(yy / 400)
  LeapYears = Leap004 - Leap100 + Leap400
  SmblYears = yy - LeapYears
  Leap = CLng(LeapYears * 366)
  Smbl = CLng(SmblYears * 365)
  
  '  Day(DateSerial(yy + 1, 3, 0))
  If Day(DateSerial(yy + 1, 3, 1) - 1) = 29 Then
    Leap = Leap + (inDate - DateSerial(yy, 12, 31))
  Else
    Smbl = Smbl + (inDate - DateSerial(yy, 12, 31))
  End If
  
  Return
End Function
 

Accessna

Registered User.
Local time
Today, 10:57
Joined
Oct 4, 2015
Messages
15
Hi,
my English is weak, I hope you understand me.

- Datediff will not give same result of GetYears Function.
- This function for Gregorian Calendar only, not for the International Calendar which is compound between Julian & Gregorian.

Regards.
 

Galaxiom

Super Moderator
Staff member
Local time
Tomorrow, 03:57
Joined
Jan 20, 2009
Messages
12,863
- Datediff will not give same result of GetYears Function.

The only difference between your GetYears and DateDiff when calculating years is that you are returning a Double rather than a Long so GetYears can show the fractional parts of a year.

- This function for Gregorian Calendar only, not for the International Calendar which is compound between Julian & Gregorian.

There is no calendar difference. The calendar used by the DateDiff function is wholly Gregorian. As I pointed out in my first post, it does not account for the days that were skipped on the change from the Julian Calendar because this would required dozens of regional differences to be managed.
 

Users who are viewing this thread

Top Bottom