C#计算年龄的代码实现

在实际开发中有时会根据生日 DateTime 即出生年月日计算出现在的年龄,可以使用下面的代码快速实现。

// 当前日期.
var today = DateTime.Today;
// 计算年龄.
var age = today.Year - birthdate.Year;
// 判断生日是否已过,返回真实年龄
if (birthdate > today.AddYears(-age)) age--;