如何根据DateTime类型的生日计算某人的年龄? [英] How do I calculate someone's age based on a DateTime type birthday?
本文介绍了如何根据DateTime类型的生日计算某人的年龄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个代表一个人生日的 DateTime
,我如何计算他们的年龄(以岁为单位)?
Given a DateTime
representing a person's birthday, how do I calculate their age in years?
推荐答案
简单易懂的解决方案.
// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;
However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.
这篇关于如何根据DateTime类型的生日计算某人的年龄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文