从日期时间选择器计算年龄 [英] Calculate The Age From Date Time Picker
本文介绍了从日期时间选择器计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个日期时间选择器和一个文本框。
我希望当我从日期时间选择器中选择日期时,年龄将自动计算我从中选择的日期日期时间选择器和年龄显示在该文本框中。
I have one datetime picker and one textbox.
I want that when i select date from datetime picker the age will automatically calculate acording to date which i select from datetime picker and the age is display in that textbox.
推荐答案
// dt1 is the date picked by the user
TimeSpan ts = DateTime.Now - dt1;
https://msdn.microsoft.com/en-us/library/system.timespan。 aspx [ ^ ]
试试这个样本并使其适应你的表格:
Try this sample and adapt it to your form:
using System;
public class Program
{
public static void Main()
{
//DateTime dob = dateTimePicker1.Value; // assuming dateTimePicker1 is used
DateTime dob = new DateTime(1995, 2, 10);
DateTime today = DateTime.Today;
int age = today.Year - dob.Year;
if (dob.AddYears(age) > today)
{
age--;
}
Console.WriteLine(age);
}
}
参考: DateTimePicker.Value Property [ ^ ]
这篇关于从日期时间选择器计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文