Determine Age from Birthday Using DateTime
Many applications require calculating a person's age from their birthdate. Here's a concise and effective method using DateTime objects.
Method:
This approach offers a clean solution:
<code class="language-csharp">// Get today's date. DateTime today = DateTime.Today; // Calculate the age. int age = today.Year - birthdate.Year; // Adjust for cases where the birthday hasn't occurred yet this year. if (birthdate.Date > today.AddYears(-age)) age--;</code>
This code efficiently calculates the age difference. It's important to remember that this calculation uses the Western age calculation method, not the East Asian system.
The above is the detailed content of How Can I Calculate a Person's Age from Their Birthday Using DateTime?. For more information, please follow other related articles on the PHP Chinese website!