vb.net 在带有日期时间选择器的文本框中以年、月或日为单位计算年龄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24171538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:41:17  来源:igfitidea点击:

Calculate age in years, months or days in textbox w/datetimepicker

vb.netdatetimepicker

提问by TecZr

my question is how can I calculate age using datetimepicker in another textbox?

我的问题是如何在另一个文本框中使用 datetimepicker 计算年龄?

e.g. If user picks a 10/06/2014 date assuming today is 11/06/2014, textbox should show "1 day" or if user picks 02/03/2014, txtbox should show "3 months"

例如,如果用户选择 10/06/2014 日期假设今天是 11/06/2014,则文本框应显示“1 天”,或者如果用户选择 02/03/2014,则文本框应显示“3 个月”

This is my code for calculate age in years

这是我计算年龄的代码

Private Sub BirthDate_ValueChanged(ByVal sender As System.Object, 
        ByVal e As System.EventArgs) Handles BirthDate.ValueChanged
    txtAge.Text = Fix((DateDiff(DateInterval.Day, BirthDate.Value, Now.Date)) / 365) & " years"
End Sub

Thanks in advance!

提前致谢!

回答by Fdisk

Check out the DateDiff specification: http://msdn.microsoft.com/en-us/library/b5xbyt6f%28v=vs.90%29.aspx

查看 DateDiff 规范:http: //msdn.microsoft.com/en-us/library/b5xbyt6f%28v=vs.90%29.aspx

You're already using it, but if you want years, you don't need to divide the days by 365, you can use DateInterval.Year.

您已经在使用它,但是如果您想要年份,则不需要将天数除以 365,您可以使用 DateInterval.Year。

You can apply the same thing to other time intervals, you'll need to set parameters for when you'd like to use each.

您可以将相同的内容应用于其他时间间隔,您需要为每个时间间隔设置参数。

For example (pseudocode):

例如(伪代码):

if DateDiff(DateInterval.Day, Birthdate.Value, Now.Date) < 30
print DateDiff(DateInterval.Day, Birthdate.Value, Now.Date)

elseif 29 < DateDiff(DateInterval.Day, Birthdate.Value, Now.Date) < 365
print DateDiff(DateInterval.Month, Birthdate.Value, Now.Date)

elseif DateDiff(DateInterval.Day, Birthdate.Value, Now.Date) > 365
print DateDiff(DateInterval.Year, Birthdate.Value, Now.Date)

I hope this helps!

我希望这有帮助!