Page 2 of 2

Re: What is the easiest way to get years, months and days?

Posted: Sunday 1st January 2023 8:41pm
by BruceSteers
Right i got it working like this :)
(tested correct with the dates you gave in the last post)

Public Sub TimeSpan(date1 As String, date2 As String) As String

  Dim d1 As Date = CDate(Val(date1))
  Dim d2 As Date = CDate(Val(date2))
  Dim yr, mn, dy, add As Integer

  yr = DateDiff(d1, d2, gb.Year)
  If Month(d1) > Month(d2) Then Dec yr
  d1 = DateAdd(d1, gb.Year, yr)

  mn = DateDiff(d1, d2, gb.Month)
  If Day(d1) > Day(d2) Then 
    Dec mn
    add = 1
  Endif

  d1 = DateAdd(d1, gb.Month, mn)
  dy = DateDiff(d1, d2, gb.Day) + add

  Return Subst("&1 years &2 months &3 days", yr, mn, dy)

End


Just needed to note if the year/month/day being checked was before or after and adjust accordingly
Passed like this..
Print TimeSpan("10/12/2022", "29/12/2022") 
Print TimeSpan("19/10/2021", "09/12/2022") 
Print TimeSpan("26/09/2015", "14/06/2021") 
Print TimeSpan("29/09/1998", "04/10/2021") 
My Console wrote: 0 years 0 months 19 days
1 years 1 months 21 days
5 years 8 months 20 days
23 years 0 months 6 days
Cheers for the puzzle :)

Re: What is the easiest way to get years, months and days?

Posted: Sunday 1st January 2023 9:58pm
by gambafeliz
:o :shock:
Ole !!!
For me you are a machine. Thank you for your masterful solution

Re: What is the easiest way to get years, months and days?

Posted: Wednesday 4th January 2023 1:47pm
by gambafeliz
Hi BruceS

With your permission, I have corrected the code because it fails with this date:
DD/MM/YYYY
04/01/2023
02/01/2026

Code: Select all

Public Sub TimeSpan(date1 As String, date2 As String) As String
 
  Dim d1 As Date = CDate(Val(date1))
  Dim d2 As Date = CDate(Val(date2))
  Dim yr, mn, dy, add As Integer
 
  yr = DateDiff(d1, d2, gb.Year)
  If Month(d1) > Month(d2) Then Dec yr
  If Month(d1) = Month(d2) And Day(d1) > Day(d2) Then Dec yr   ' ADD
  d1 = DateAdd(d1, gb.Year, yr)
 
  mn = DateDiff(d1, d2, gb.Month)
  If Day(d1) > Day(d2) Then 
    Dec mn
    add = 1
  Endif
 
  d1 = DateAdd(d1, gb.Month, mn)
  dy = DateDiff(d1, d2, gb.Day) + add
 
  Return Subst("&1 years &2 months &3 days", yr, mn, dy)
 
End