vb.net 使用当前年份计算年龄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17851944/
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 14:23:20  来源:igfitidea点击:

Age calculation using current year

vb.net

提问by Das Sir

I am a VB.NET beginner and i would like to ask how one can calculate age of a person if only the year of birth is entered in a text box in a form. I am supposed to use the current year minus the year of birth but i don't really have the code. here is the problem : there is a text box named txtdob in a form where the user is required to enter his/her year of birth. I need a code that determines the age of the user using the current YEAR and the year of birth entered.

我是一名 VB.NET 初学者,我想问一下如果只在表单的文本框中输入出生年份,如何计算一个人的年龄。我应该使用当前年份减去出生年份,但我真的没有代码。问题是:有一个名为 txtdob 的文本框,需要用户输入他/她的出生年份。我需要一个使用当前年份和输入的出生年份来确定用户年龄的代码。

回答by matzone

Use TimeSpan.. Do substract Now to Your Date ..

使用TimeSpan.. 将现在减去您的日期 ..

Dim dBirth as Date
Dim nDiff as TimeSpan

dBirth = ........  ' you fill with yours

nDiff = Now.Substract(dBirth)

Msgbox( format(nDiff.Days/365) ) '--------> will show the age ..

回答by Tim Schmelter

Use Integer.Parseor Integer.TryParseand then calculate it from Date.Now:

使用Integer.ParseInteger.TryParse然后计算它Date.Now

Dim birthYear As Int32
If Int32.TryParse(txtAge.Text, birthYear) Then
    Dim age As Int32 = Date.Now.Year - birthYear
    MessageBox.Show("Your age is: " & age)
Else
    MessageBox.Show("Please enter a valid year of birth")
End If

回答by Louis van Tonder

Have not tested this, but it should get you going...

没有测试过这个,但它应该让你去......

yyyy is the birth year....

yyyy 是出生年份....

now.subtract(cdate("0/0/yyyy")).totalyears

Cheers

干杯

回答by Slava

Have a look at the DateDiff function. It tells you the difference between two dates, and you can specify the DateInterval to be Year, eg

看看 DateDiff 函数。它告诉您两个日期之间的差异,您可以将 DateInterval 指定为 Year,例如

Dim difference As Int = DateDiff(DateInterval.Year, dateOfBirth, currentDate)

Link to the resource: http://msdn.microsoft.com/en-us/library/b5xbyt6f(v=vs.80).aspx

资源链接:http: //msdn.microsoft.com/en-us/library/b5xbyt6f(v=vs.80).aspx