如何根据 DateTime 类型的生日计算某人的年龄? [英] How do I calculate someone's age based on a DateTime type birthday?

查看:24
本文介绍了如何根据 DateTime 类型的生日计算某人的年龄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个表示某人生日的 DateTime,我如何计算他们的年龄(以年为单位)?

Given a DateTime representing a person's birthday, how do I calculate their age in years?

推荐答案

易于理解且简单的解决方案.

An easy to understand and simple solution.

// 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆