1

I have read questions like this: How do I calculate someone's age in C#?. Say I wanted to establish whether a date of birth makes a person over 21 years old. Could I do this:

if (dateOfBirth.Date <= DateTime.Now.AddYears(-21).Date 
{
 //Do something because the person is over 21.
}

Here I have just one line of code to get the age. The approaches in the other question have two or more - that is why I am asking. Is my approach slower or something?

w0051977
  • 15,099
  • 32
  • 152
  • 329

2 Answers2

0

This looks fine. The other question you linked to is a different because it's calculating the age. You don't care what the actual age is – you just want to know if it's greater than 21.

asherber
  • 2,508
  • 1
  • 15
  • 12
  • Surely the fact that I want to know if the person is over 21 means that I do care about what the age is? – w0051977 Feb 04 '18 at 14:23
  • You don't care about the exact age. Your code determines the date on which someone who is exactly 21 year old was born (`DateTime.Now.AddYears(-21).Date`) and then looks to see if the person was born on or before that date. He could be 21, or 22, or 52 – you don't know and you don't care. – asherber Feb 04 '18 at 14:28
  • I see. I guess this is a better approach, then the approach used in the other question (for my specific case). – w0051977 Feb 04 '18 at 14:30
  • Please see my question here: https://softwareengineering.stackexchange.com/questions/365234/initialise-a-date-of-birth-with-a-datetime-or-three-integers and specifically gnasher729 comment under Arseni's answer. If all my users use the western idea of age (rather than East Asian Reckoning) then I assume that I do not have an issue? – w0051977 Feb 04 '18 at 19:47
0

I think its okay approach. You are talking about speed (your approach is slower or ok), I dont see any other fast way to check age is 21 or over.

Following code is just another way:

if (dateOfBirth.AddYears(21).Date <= DateTime.Now.Date)
{
 //Do something because the person is over 21.
}

Its similar to your code, just not reducing date but incrementing and comparing.

I had a thought that could addition be faster than subtraction so I suggested above but just realized that

The only difference then between adding and subtracting is The Inversion that takes place. So any time diffences between Adding and Subtracting are neglibile, and much shorter than the CPU clock period. And since the CPU only advances on the clock, both Add/Subtract are of the same speed.

SSD
  • 1,373
  • 2
  • 13
  • 20
  • Is your approach "better"? – w0051977 Feb 04 '18 at 14:43
  • I was thinking Yes. But Add subtract are same speed. You can choose any. Edited answer – SSD Feb 04 '18 at 14:49
  • Please see gnasher729 comment here: https://stackoverflow.com/questions/48608888/calculate-age-using-dob. Are you sure this is an accurate way of figuring out the DOB? – w0051977 Feb 04 '18 at 18:59