Home >Backend Development >C++ >How Do I Calculate a Person's Age from Their DateTime Birthday?

How Do I Calculate a Person's Age from Their DateTime Birthday?

Susan Sarandon
Susan SarandonOriginal
2025-02-02 07:51:09821browse

How Do I Calculate a Person's Age from Their DateTime Birthday?

Calculate the age according to DateTime's birthday

This article introduces how to calculate a person's age based on the birthday of DateTime.

Solution:

Calculate a person's age (in the year) based on the birthday of the DateTime type, please follow the steps below:

Store today's date in a variable called

.
  1. Calculate the age by subtracting the birthday of the year: today.
  2. By evaluating whether the person has been in the current year to adjust the leap year. If not, you will be reduced by 1. age = today.Year - birthdate.Year
  3. Note:
<code class="language-csharp">// 保存今天的日期。
var today = DateTime.Today;

// 计算年龄。
var age = today.Year - birthdate.Year;

// 如果是闰年,则返回到此人出生的年份
if (birthdate.Date > today.AddYears(-age)) age--;</code>

This solution assumes that the concept of age is generally consistent with Western culture. If you need different cultural age definitions, such as East Asia's calculation methods, other factors may be considered.

The above is the detailed content of How Do I Calculate a Person's Age from Their DateTime Birthday?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn