如何在C#.net中计算一个人的年龄 [英] How to calculte a person's age in C#.net

查看:104
本文介绍了如何在C#.net中计算一个人的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个代码,通过从用户那里获取生日来计算一个人的年龄。使用日期时间函数。

I want to write a code to calculate a person''s age by taking birthdate from the user. Using datetime function.

推荐答案

嗯。为什么MSDN帮助没有告诉你那个?它看起来很明显:



Hm. How come the MSDN help did not tell you that? It looks so obvious:

System.DateTime birthTime = AskTheUser(myUser); // :-)
System.DateTime now = System.DateTime.Now;
System.TimeSpan age = now - birthTime; //as simple as that
double ageInDays = age.TotalDays; // will you convert to whatever you want yourself?





-SA


DateTime birthdate = new DateTime(1981, 1, 7);
DateTime now = DateTime.Now;
int years = now.Year - birthdate.Year;
if (now.Month < birthdate.Month || (now.Month == birthdate.Month && now.Day < birthdate.Day))
  years--;
MessageBox.Show(years.ToString());


使用 时间段库 [ ^ ]:

Using the Time Period Library[^]:
// ----------------------------------------------------------------------
public void AgeSample( DateTime birthDay )
{
  // output: x Year x Months
  Console.WriteLine( new DateDiff( birthDay ).GetDescription( 2 ) );
} // AgeSample


这篇关于如何在C#.net中计算一个人的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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