Home >Backend Development >C++ >How Can I Calculate a Person's Age from Their Birthdate Using DateTime?

How Can I Calculate a Person's Age from Their Birthdate Using DateTime?

Linda Hamilton
Linda HamiltonOriginal
2025-02-02 07:41:101149browse

How Can I Calculate a Person's Age from Their Birthdate Using DateTime?

Using DateTime to calculate the age corresponding to the birth date

A person's age is very simple to calculate the age of a person based on the birth date of the DateTime type.

Solution:

First, get the current date to the Datetime variable named TODAY. Then, calculate the difference between the current year and the yeardate.year as the age of the person. The code is as follows:

Leap year adjustment:

<code>var today = DateTime.Today;
var age = today.Year - birthdate.Year;</code>
If the birth date of the person coincides with the leap year, it needs to be adjusted. If the person's birthday has not passed that year, he should reduce the age by one. This can be achieved by comparing BIRTHDATE.DATE and TODAY.ADDYEARS (-AGE):

Note:

This solution calculates age based on the concept of Western age. If the East Asian algorithm is required, further modification may be required.
<code>if (birthdate.Date > today.AddYears(-age)) age--;</code>

The above is the detailed content of How Can I Calculate a Person's Age from Their Birthdate Using DateTime?. 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