Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. The Weird and The Wonderful
  4. MSDN example [modified] (oops, my bad!)

MSDN example [modified] (oops, my bad!)

Scheduled Pinned Locked Moved The Weird and The Wonderful
phpvisual-studiolinqcombeta-testing
20 Posts 8 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L leppie

    public static int GetAge(string birthDate)
    {
    DateTime birth;

    try
    {
    birth = DateTime.Parse(birthDate);
    }
    catch (Exception ex)
    {
    throw new ApplicationException("Unable to read birth date.", ex);
    }

    if (DateTime.Today.Month < birth.Month) //it is before your birthday
    {
    return DateTime.Today.Year - birth.Year - 1;
    }
    else if (DateTime.Today.Month > birth.Month) //it is after your birthday
    {
    return DateTime.Today.Year - birth.Year;
    }
    else // DateTime.Today.Month == birth.Month //we don't know yet
    {
    if (DateTime.Today.Day < birth.Day) //it is before your birthday
    {
    return DateTime.Today.Year - birth.Year - 1;
    }
    else //it is your birthday, or it is after your birthday
    {
    return DateTime.Today.Year - birth.Year;
    }
    }
    }

    :sigh: :doh: To be seen @ http://msdn.microsoft.com/en-us/library/bb126477.aspx[^] UPDATE: I was under the impression, Timespan had a TotalYears property. But now, looking at the logic, I can see why it does not have one. :-O

    xacc.ide - now with TabsToSpaces support
    IronScheme - 1.0 beta 2 - out now!
    ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

    modified on Wednesday, April 15, 2009 10:40 AM

    OriginalGriffO Offline
    OriginalGriffO Offline
    OriginalGriff
    wrote on last edited by
    #2

    Yes. Ok. This is a bit easier on the eye...

        public static int GetAge(string birthDate)
            {
            DateTime birth;
            try
                {
                birth = DateTime.Parse(birthDate);
                }
            catch (Exception ex)
                {
                throw new ApplicationException("Unable to read birth date.", ex);
                }
            DateTime now = DateTime.Today;
            if (now.DayOfYear < birth.DayOfYear)
                {
                // Before your birthday
                return now.Year - birth.Year - 1;
                }
            return now.Year - birth.Year;
            }
    

    Oh, and it works around midnight, too...

    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
    "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

    L 0 S 4 Replies Last reply
    0
    • OriginalGriffO OriginalGriff

      Yes. Ok. This is a bit easier on the eye...

          public static int GetAge(string birthDate)
              {
              DateTime birth;
              try
                  {
                  birth = DateTime.Parse(birthDate);
                  }
              catch (Exception ex)
                  {
                  throw new ApplicationException("Unable to read birth date.", ex);
                  }
              DateTime now = DateTime.Today;
              if (now.DayOfYear < birth.DayOfYear)
                  {
                  // Before your birthday
                  return now.Year - birth.Year - 1;
                  }
              return now.Year - birth.Year;
              }
      

      Oh, and it works around midnight, too...

      L Offline
      L Offline
      leppie
      wrote on last edited by
      #3

      Oh dear! Another one bites the dust! :sigh: bad hint: TimeSpan UPDATE: Sorry :)

      xacc.ide - now with TabsToSpaces support
      IronScheme - 1.0 beta 2 - out now!
      ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

      modified on Wednesday, April 15, 2009 10:58 AM

      L 1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        Yes. Ok. This is a bit easier on the eye...

            public static int GetAge(string birthDate)
                {
                DateTime birth;
                try
                    {
                    birth = DateTime.Parse(birthDate);
                    }
                catch (Exception ex)
                    {
                    throw new ApplicationException("Unable to read birth date.", ex);
                    }
                DateTime now = DateTime.Today;
                if (now.DayOfYear < birth.DayOfYear)
                    {
                    // Before your birthday
                    return now.Year - birth.Year - 1;
                    }
                return now.Year - birth.Year;
                }
        

        Oh, and it works around midnight, too...

        0 Offline
        0 Offline
        0x3c0
        wrote on last edited by
        #4

        Why not just use something like this?

        public static int GetAge(string birthDate)
        {
        DateTime birth;
        TimeSpan livingAge; /* This will be inaccurate by the time it's
        * been calculated but I don't think the user
        * will care about a few ticks */

        if(!DateTime.Parse(birthDate, out birth))
            throw new InvalidCastException("Unable to parse birth date");
        livingAge = DateTime.Now - birth;
        return (livingAge + DateTime.MinValue).Years - 1;
        

        }

        L L 3 Replies Last reply
        0
        • 0 0x3c0

          Why not just use something like this?

          public static int GetAge(string birthDate)
          {
          DateTime birth;
          TimeSpan livingAge; /* This will be inaccurate by the time it's
          * been calculated but I don't think the user
          * will care about a few ticks */

          if(!DateTime.Parse(birthDate, out birth))
              throw new InvalidCastException("Unable to parse birth date");
          livingAge = DateTime.Now - birth;
          return (livingAge + DateTime.MinValue).Years - 1;
          

          }

          L Offline
          L Offline
          Luc 648011
          wrote on last edited by
          #5

          Huh? either you want an exception, so you use Parse; or you don't want one and use TryParse. :)

          0 1 Reply Last reply
          0
          • L leppie

            Oh dear! Another one bites the dust! :sigh: bad hint: TimeSpan UPDATE: Sorry :)

            xacc.ide - now with TabsToSpaces support
            IronScheme - 1.0 beta 2 - out now!
            ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

            modified on Wednesday, April 15, 2009 10:58 AM

            L Offline
            L Offline
            Luc 648011
            wrote on last edited by
            #6

            Part of the ugly code is due to the fact that TimeSpan does not have Months or Years properties; [EDITED] while it's MaxValue corresponds to more than 10 million days, without knowing the reference it can't decide on how many days fit in a month, and how leap years need handled. [/EDITED] :)

            modified on Wednesday, April 15, 2009 9:52 AM

            L 1 Reply Last reply
            0
            • L leppie

              public static int GetAge(string birthDate)
              {
              DateTime birth;

              try
              {
              birth = DateTime.Parse(birthDate);
              }
              catch (Exception ex)
              {
              throw new ApplicationException("Unable to read birth date.", ex);
              }

              if (DateTime.Today.Month < birth.Month) //it is before your birthday
              {
              return DateTime.Today.Year - birth.Year - 1;
              }
              else if (DateTime.Today.Month > birth.Month) //it is after your birthday
              {
              return DateTime.Today.Year - birth.Year;
              }
              else // DateTime.Today.Month == birth.Month //we don't know yet
              {
              if (DateTime.Today.Day < birth.Day) //it is before your birthday
              {
              return DateTime.Today.Year - birth.Year - 1;
              }
              else //it is your birthday, or it is after your birthday
              {
              return DateTime.Today.Year - birth.Year;
              }
              }
              }

              :sigh: :doh: To be seen @ http://msdn.microsoft.com/en-us/library/bb126477.aspx[^] UPDATE: I was under the impression, Timespan had a TotalYears property. But now, looking at the logic, I can see why it does not have one. :-O

              xacc.ide - now with TabsToSpaces support
              IronScheme - 1.0 beta 2 - out now!
              ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

              modified on Wednesday, April 15, 2009 10:40 AM

              I Offline
              I Offline
              Ian Shlasko
              wrote on last edited by
              #7

              It needs to be done in true OOP style...

              public static int GetAge(string birthDate)
              {
              DateTimeParser dtpc = new DateTimeParser() { DateAsString = birthDate };
              DateTimeWithoutYearComparer dtwyc = new DateTimeWithoutYearComparer();

              return dtwyc.PerformComparisonAndReturnDifferenceInYears(DateTime.Today, dtpc.Parse());
              }

              public class DateTimeParser
              {
              public string DateAsString { get; set; }
              public DateTime Parse()
              {
              throw new NotImplementedException("We're too lazy to actually write code");
              }
              }

              public class DateTimeWithoutYearComparer
              {
              public DateTimeWithoutYearComparer()
              {
              InitializeComponent();
              }

              private void InitializeComponent()
              {
              // Here there be dragons
              }

              public int PerformComparisonAndReturnDifferenceInYears(DateTime a, DateTime b)
              {
              /* The team would like to congratulate Bill Lumbergh for winning
              * the "Think of the Longest and Dumbest Name for a Function" contest.
              */
              return 42;
              }
              }

              Sorry, I was reading that thread in the Lounge about funny code comments, and, well, my mind is pretty warped to begin with... The scary thing is that if I typed this into Visual Studio instead of here, I think it might actually compile (and crash).

              1 Reply Last reply
              0
              • L Luc 648011

                Huh? either you want an exception, so you use Parse; or you don't want one and use TryParse. :)

                0 Offline
                0 Offline
                0x3c0
                wrote on last edited by
                #8

                It's just my rather broken coding style. I never learned one formally. If you wanted, you could replace the throw statement with return -1

                1 Reply Last reply
                0
                • L leppie

                  public static int GetAge(string birthDate)
                  {
                  DateTime birth;

                  try
                  {
                  birth = DateTime.Parse(birthDate);
                  }
                  catch (Exception ex)
                  {
                  throw new ApplicationException("Unable to read birth date.", ex);
                  }

                  if (DateTime.Today.Month < birth.Month) //it is before your birthday
                  {
                  return DateTime.Today.Year - birth.Year - 1;
                  }
                  else if (DateTime.Today.Month > birth.Month) //it is after your birthday
                  {
                  return DateTime.Today.Year - birth.Year;
                  }
                  else // DateTime.Today.Month == birth.Month //we don't know yet
                  {
                  if (DateTime.Today.Day < birth.Day) //it is before your birthday
                  {
                  return DateTime.Today.Year - birth.Year - 1;
                  }
                  else //it is your birthday, or it is after your birthday
                  {
                  return DateTime.Today.Year - birth.Year;
                  }
                  }
                  }

                  :sigh: :doh: To be seen @ http://msdn.microsoft.com/en-us/library/bb126477.aspx[^] UPDATE: I was under the impression, Timespan had a TotalYears property. But now, looking at the logic, I can see why it does not have one. :-O

                  xacc.ide - now with TabsToSpaces support
                  IronScheme - 1.0 beta 2 - out now!
                  ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                  modified on Wednesday, April 15, 2009 10:40 AM

                  Y Offline
                  Y Offline
                  Yusuf
                  wrote on last edited by
                  #9

                  where do you think, the horror codes, plz send codz now, my code no work... stem from?

                  Yusuf Oh didn't you notice, analogous to square roots, they recently introduced rectangular, circular, and diamond roots to determine the size of the corresponding shapes when given the area. Luc Pattyn[^]

                  1 Reply Last reply
                  0
                  • L Luc 648011

                    Part of the ugly code is due to the fact that TimeSpan does not have Months or Years properties; [EDITED] while it's MaxValue corresponds to more than 10 million days, without knowing the reference it can't decide on how many days fit in a month, and how leap years need handled. [/EDITED] :)

                    modified on Wednesday, April 15, 2009 9:52 AM

                    L Offline
                    L Offline
                    leppie
                    wrote on last edited by
                    #10

                    Arggh, I could swear TimeSpan had those properties! Now I feel like the fool! :-O

                    xacc.ide - now with TabsToSpaces support
                    IronScheme - 1.0 beta 2 - out now!
                    ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                    1 Reply Last reply
                    0
                    • 0 0x3c0

                      Why not just use something like this?

                      public static int GetAge(string birthDate)
                      {
                      DateTime birth;
                      TimeSpan livingAge; /* This will be inaccurate by the time it's
                      * been calculated but I don't think the user
                      * will care about a few ticks */

                      if(!DateTime.Parse(birthDate, out birth))
                          throw new InvalidCastException("Unable to parse birth date");
                      livingAge = DateTime.Now - birth;
                      return (livingAge + DateTime.MinValue).Years - 1;
                      

                      }

                      L Offline
                      L Offline
                      leppie
                      wrote on last edited by
                      #11

                      Cool, not what I had in mind, but definitely better than what I had in mind! :)

                      xacc.ide - now with TabsToSpaces support
                      IronScheme - 1.0 beta 2 - out now!
                      ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                      0 L 2 Replies Last reply
                      0
                      • L leppie

                        Cool, not what I had in mind, but definitely better than what I had in mind! :)

                        xacc.ide - now with TabsToSpaces support
                        IronScheme - 1.0 beta 2 - out now!
                        ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                        0 Offline
                        0 Offline
                        0x3c0
                        wrote on last edited by
                        #12

                        Thanks. For what its worth, what did you have in mind?

                        L 1 Reply Last reply
                        0
                        • 0 0x3c0

                          Thanks. For what its worth, what did you have in mind?

                          L Offline
                          L Offline
                          leppie
                          wrote on last edited by
                          #13

                          Computafreak wrote:

                          For what its worth, what did you have in mind?

                          For some reason I thought Timespan had a TotalYears property... :doh:

                          xacc.ide - now with TabsToSpaces support
                          IronScheme - 1.0 beta 2 - out now!
                          ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                          1 Reply Last reply
                          0
                          • L leppie

                            Cool, not what I had in mind, but definitely better than what I had in mind! :)

                            xacc.ide - now with TabsToSpaces support
                            IronScheme - 1.0 beta 2 - out now!
                            ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                            L Offline
                            L Offline
                            Luc 648011
                            wrote on last edited by
                            #14

                            yet incorrect, since it assumes months and leap years evolve from day of birth in the same way as they do from DateTime.MinValue The net result is that close to one's birthday the formula can be off by 1. This one is much safer, although still not perfect: DateTime.Today.Subtract(DateTime.Parse(birthday)).Days/365.242374 The perfect solution really uses ToDay.Years-DateTime.Parse(birthday).Years and adjusts by one according to the result of ToDay.DayOfYear < DateTime.Parse(birthday).DayOfYear :)

                            L 1 Reply Last reply
                            0
                            • 0 0x3c0

                              Why not just use something like this?

                              public static int GetAge(string birthDate)
                              {
                              DateTime birth;
                              TimeSpan livingAge; /* This will be inaccurate by the time it's
                              * been calculated but I don't think the user
                              * will care about a few ticks */

                              if(!DateTime.Parse(birthDate, out birth))
                                  throw new InvalidCastException("Unable to parse birth date");
                              livingAge = DateTime.Now - birth;
                              return (livingAge + DateTime.MinValue).Years - 1;
                              

                              }

                              L Offline
                              L Offline
                              leppie
                              wrote on last edited by
                              #15

                              Actually, after carefully looking at your solution, it appears to be wrong.

                              xacc.ide - now with TabsToSpaces support
                              IronScheme - 1.0 beta 2 - out now!
                              ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                              0 1 Reply Last reply
                              0
                              • L Luc 648011

                                yet incorrect, since it assumes months and leap years evolve from day of birth in the same way as they do from DateTime.MinValue The net result is that close to one's birthday the formula can be off by 1. This one is much safer, although still not perfect: DateTime.Today.Subtract(DateTime.Parse(birthday)).Days/365.242374 The perfect solution really uses ToDay.Years-DateTime.Parse(birthday).Years and adjusts by one according to the result of ToDay.DayOfYear < DateTime.Parse(birthday).DayOfYear :)

                                L Offline
                                L Offline
                                leppie
                                wrote on last edited by
                                #16

                                Ahh yes, I just noticed that 2 minutes ago :)

                                xacc.ide - now with TabsToSpaces support
                                IronScheme - 1.0 beta 2 - out now!
                                ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                                1 Reply Last reply
                                0
                                • L leppie

                                  Actually, after carefully looking at your solution, it appears to be wrong.

                                  xacc.ide - now with TabsToSpaces support
                                  IronScheme - 1.0 beta 2 - out now!
                                  ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                                  0 Offline
                                  0 Offline
                                  0x3c0
                                  wrote on last edited by
                                  #17

                                  Ah, well. Live and learn

                                  1 Reply Last reply
                                  0
                                  • OriginalGriffO OriginalGriff

                                    Yes. Ok. This is a bit easier on the eye...

                                        public static int GetAge(string birthDate)
                                            {
                                            DateTime birth;
                                            try
                                                {
                                                birth = DateTime.Parse(birthDate);
                                                }
                                            catch (Exception ex)
                                                {
                                                throw new ApplicationException("Unable to read birth date.", ex);
                                                }
                                            DateTime now = DateTime.Today;
                                            if (now.DayOfYear < birth.DayOfYear)
                                                {
                                                // Before your birthday
                                                return now.Year - birth.Year - 1;
                                                }
                                            return now.Year - birth.Year;
                                            }
                                    

                                    Oh, and it works around midnight, too...

                                    L Offline
                                    L Offline
                                    leppie
                                    wrote on last edited by
                                    #18

                                    Good answer in fact :)

                                    xacc.ide - now with TabsToSpaces support
                                    IronScheme - 1.0 beta 2 - out now!
                                    ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                                    1 Reply Last reply
                                    0
                                    • L leppie

                                      public static int GetAge(string birthDate)
                                      {
                                      DateTime birth;

                                      try
                                      {
                                      birth = DateTime.Parse(birthDate);
                                      }
                                      catch (Exception ex)
                                      {
                                      throw new ApplicationException("Unable to read birth date.", ex);
                                      }

                                      if (DateTime.Today.Month < birth.Month) //it is before your birthday
                                      {
                                      return DateTime.Today.Year - birth.Year - 1;
                                      }
                                      else if (DateTime.Today.Month > birth.Month) //it is after your birthday
                                      {
                                      return DateTime.Today.Year - birth.Year;
                                      }
                                      else // DateTime.Today.Month == birth.Month //we don't know yet
                                      {
                                      if (DateTime.Today.Day < birth.Day) //it is before your birthday
                                      {
                                      return DateTime.Today.Year - birth.Year - 1;
                                      }
                                      else //it is your birthday, or it is after your birthday
                                      {
                                      return DateTime.Today.Year - birth.Year;
                                      }
                                      }
                                      }

                                      :sigh: :doh: To be seen @ http://msdn.microsoft.com/en-us/library/bb126477.aspx[^] UPDATE: I was under the impression, Timespan had a TotalYears property. But now, looking at the logic, I can see why it does not have one. :-O

                                      xacc.ide - now with TabsToSpaces support
                                      IronScheme - 1.0 beta 2 - out now!
                                      ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                                      modified on Wednesday, April 15, 2009 10:40 AM

                                      L Offline
                                      L Offline
                                      Lutoslaw
                                      wrote on last edited by
                                      #19

                                      public static int GetAge(string birthDate)
                                      {
                                      throw new CoderIsABoorException();
                                      }

                                      Greetings - Gajatko Portable.NET is part of DotGNU, a project to build a complete Free Software replacement for .NET - a system that truly belongs to the developers.

                                      1 Reply Last reply
                                      0
                                      • OriginalGriffO OriginalGriff

                                        Yes. Ok. This is a bit easier on the eye...

                                            public static int GetAge(string birthDate)
                                                {
                                                DateTime birth;
                                                try
                                                    {
                                                    birth = DateTime.Parse(birthDate);
                                                    }
                                                catch (Exception ex)
                                                    {
                                                    throw new ApplicationException("Unable to read birth date.", ex);
                                                    }
                                                DateTime now = DateTime.Today;
                                                if (now.DayOfYear < birth.DayOfYear)
                                                    {
                                                    // Before your birthday
                                                    return now.Year - birth.Year - 1;
                                                    }
                                                return now.Year - birth.Year;
                                                }
                                        

                                        Oh, and it works around midnight, too...

                                        S Offline
                                        S Offline
                                        supercat9
                                        wrote on last edited by
                                        #20

                                        For that approach to work, wouldn't you have to add 306 days to both the birthdate and the present time before using the Year and DayOfYear properties? The notion that someone born on 2/28/2000 would have had to wait 366 days to be "one year old", while someone born on 3/1/2000 would only have to wait 365 days, is somewhat artificial but it is certainly well-established. #2/28/2000#.DayOfYear == 59 #2/28/2001#.DayOfYear == 59 #3/1/2000#.DayOfYear == 61 #3/1/2001#.DayOfYear == 60 #2/28/2000#.AddDays(306).DayOfYear == 365 #2/28/2001#.AddDays(306).DayOfYear == 365 #3/1/2000#.AddDays(306).DayOfYear == 1 #3/1/2001#.AddDays(306).DayOfYear == 1 Of course, adding 306 days has an ugliness all its own. My own preference would probably be to simply format the thing as MMDDHHMMSS, do a string compare, and adjust the year appropriately, but another option would be to format as YYYYMMDDHHMMSS, convert to a long or double, subtract, and divide by 10,000,000,000.

                                        1 Reply Last reply
                                        0
                                        Reply
                                        • Reply as topic
                                        Log in to reply
                                        • Oldest to Newest
                                        • Newest to Oldest
                                        • Most Votes


                                        • Login

                                        • Don't have an account? Register

                                        • Login or register to search.
                                        • First post
                                          Last post
                                        0
                                        • Categories
                                        • Recent
                                        • Tags
                                        • Popular
                                        • World
                                        • Users
                                        • Groups