I have 2 dates - How old is the user (days, months and years)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DevInCode
    New Member
    • Apr 2008
    • 55

    I have 2 dates - How old is the user (days, months and years)

    I have two dates. I need to determine if the user is over 18 based on the date they entered.

    I assume I have to do something like subtract their birthdate from today, but its not exactly that straight forward.

    Any suggestions or a code sample you could point me to? That would be excellent!

    Thanks :)
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    If your dates are in DateTime objects, you can use the TimeSpan object.

    Here's an quick snippet that calculates how many years old I am...

    Code:
                DateTime bd = new DateTime(1982, 1, 9);
                DateTime now = DateTime.Now;
    
                TimeSpan ts = now - bd;
                Console.WriteLine("Years: " + ts.Days / 365.0);
    I hope that helps!

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      Note to Gary, you will want to use the .TotalDays property, not the .Days.

      Comment

      • akshaymahajan
        New Member
        • Sep 2009
        • 12

        #4
        Why can't you subtract the user entered date from System.DateTime .Now?

        I mean ... first get the Year component of both the dates and then subtract.
        Then you can check whether the difference is greater than 18 or not.

        Tell me if it works.

        Comment

        • GaryTexmo
          Recognized Expert Top Contributor
          • Jul 2009
          • 1501

          #5
          Originally posted by Plater
          Note to Gary, you will want to use the .TotalDays property, not the .Days.
          Oops, yes... Apparently I left that there from when I was testing, trying to figure out why it was telling me I was 28 years old. Let this be a lesson to all, there are 365 days in a year and 360 degrees in an angle, not the other way around.

          ;)

          Code:
          DateTime bd = new DateTime(1982, 1, 9);
          DateTime now = DateTime.Now;
          
          TimeSpan ts = now - bd;
          Console.WriteLine("Years: " + ts.TotalDays / 365.0);
          Originally posted by akshaymahajan
          Why can't you subtract the user entered date from System.DateTime .Now?

          I mean ... first get the Year component of both the dates and then subtract.
          Then you can check whether the difference is greater than 18 or not.

          Tell me if it works.
          You could probably do it... you should be able to try it out yourself fairly easily :)

          Comment

          Working...