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

New to Gambas? Post your questions here. No question is too silly or too simple.
User avatar
BruceSteers
Posts: 1521
Joined: Thursday 23rd July 2020 5:20pm
Location: Isle of Wight
Contact:

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

Post 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 :)
If at first you don't succeed , try doing something differently.
BruceS
User avatar
gambafeliz
Posts: 139
Joined: Friday 2nd September 2022 7:50pm
Location: I live in the same city as Picasso

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

Post by gambafeliz »

:o :shock:
Ole !!!
For me you are a machine. Thank you for your masterful solution
For your misfortunes I am Spanish and I only know Spanish, please, be patient with me, Thank you. :)
User avatar
gambafeliz
Posts: 139
Joined: Friday 2nd September 2022 7:50pm
Location: I live in the same city as Picasso

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

Post 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
For your misfortunes I am Spanish and I only know Spanish, please, be patient with me, Thank you. :)
Post Reply