我想从datetimepicker计算年龄。 只要用户从datetimepicker中选择日期,即可计算年龄,然后立即在年龄文本框中自动显示。 这是我在控制台应用程序都做从datetimepicker计算年龄,并立即在文本框中显示该年龄
int age = 0;
DateTime currentDate = DateTime.Parse(DateTime.Now.Date.ToShortDateString());
Console.WriteLine(currentDate);
Console.WriteLine("Please enter your birthdate");
DateTime birthdate = DateTime.Parse(Console.ReadLine());
age = currentDate.Year - birthdate.Year;
if (currentDate.Month <birthdate.Month)
{
age--;
}
else if ((currentDate.Month >= birthdate.Month)
&& (currentDate.Day < birthdate.Day))
{
age--;
}
Console.WriteLine(age);
我可以做计算的winform年龄application.But我没有经过任何想法相同的逻辑,如何显示在文本框岁这个年龄自动后瞬间用户从datetimepicker中选择了年龄。
你可以让你通过直接保存日期来提高''currentDate''的效率'DateTime currentDate = DateTime.Now.Date;'。你*不需要转换成String,然后解析回DateTime。 – Jesse 2013-03-07 09:31:48
我倾向于更容易写出int age ='(int)(DateTime.Now.Subtract(birthday).TotalDays/365.25)',它的代码更少并且更易读IMO – happygilmore 2013-03-07 09:36:54
谢谢大家。我真的很感谢你们帮帮我。我仍然在学习C#,所以我可能会问很多问题,所以在将来也可以这样帮助我。 – 2013-03-07 22:48:53