locked
Age calculator with VB2010

    Question

  • I just want to calculate age from two datetimepicker tools. The label should display - "XX years XX months xx days old". I have succeeded in calculating with respect to time, but failing w.r.t date. Any help ? I have searched most of the forums..
    Saturday, December 24, 2011 2:45 AM

Answers

  • The datetimepicker.value is a datetime object, so pass the two values to this function to get the string.  This is a "brute force" method that keeps incrimenting a date until the target date is reached.
     
     Function Age(ByVal d1 As DateTime, ByVal d2 As DateTime) As String
      Dim c As Calendar = New GregorianCalendar
      Dim y As Integer = 0, m As Integer = 0, d As Integer = 0
     
      While d1.AddYears(y) < d2
       y = y + 1
      End While
      y = y - 1
     
      While d1.AddYears(y).AddMonths(m) < d2
       m = m + 1
      End While
      m = m - 1
     
      While d1.AddYears(y).AddMonths(m).AddDays(d) < d2
       d = d + 1
      End While
     
      Return String.Format("{0} Years, {1} Months, {2} Days.", y, m, d)
     End Function

    --
    Mike
    • Proposed as answer by Ragu.R Saturday, December 24, 2011 5:23 PM
    • Marked as answer by Mike FengModerator Monday, December 26, 2011 2:13 AM
    Saturday, December 24, 2011 3:31 AM

All replies

  • Hi kunibabina,

                 will u pls share ur code.


    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful". Happy Coding...
    Saturday, December 24, 2011 2:52 AM
  • The datetimepicker.value is a datetime object, so pass the two values to this function to get the string.  This is a "brute force" method that keeps incrimenting a date until the target date is reached.
     
     Function Age(ByVal d1 As DateTime, ByVal d2 As DateTime) As String
      Dim c As Calendar = New GregorianCalendar
      Dim y As Integer = 0, m As Integer = 0, d As Integer = 0
     
      While d1.AddYears(y) < d2
       y = y + 1
      End While
      y = y - 1
     
      While d1.AddYears(y).AddMonths(m) < d2
       m = m + 1
      End While
      m = m - 1
     
      While d1.AddYears(y).AddMonths(m).AddDays(d) < d2
       d = d + 1
      End While
     
      Return String.Format("{0} Years, {1} Months, {2} Days.", y, m, d)
     End Function

    --
    Mike
    • Proposed as answer by Ragu.R Saturday, December 24, 2011 5:23 PM
    • Marked as answer by Mike FengModerator Monday, December 26, 2011 2:13 AM
    Saturday, December 24, 2011 3:31 AM
  • Thanks Family Tree Mike for your suggestion. I understood...
    Saturday, December 24, 2011 7:52 AM