使用日期时间计算年龄 [英] Calculate age using datetime
问题描述
我试图找出如果年龄介于两者之间我该怎么办,例如16-21。
我尝试了什么:
我有一个名为Person的课程。
public string 名称{获得跨度>; set ; }
public string 姓氏{ get 跨度>; set ; }
public DateTime年龄{获取; set ; }
}
我试图找出确定某些值之间的年龄。所以我们说:
人:
姓名:Blah
姓:Nah
年龄:20岁/>
我试图创建一个if语句,如果年龄介于16到21之间,则说明
等等。
我怎么能这样做?
提前谢谢。
看看这里:与年龄一起工作:它与TimeSpan不同! [ ^ ]
实际上,你不应该有年龄
DateTime属性。它应该命名为DateOfBirth
(例如)。然后可以在您需要时从出生日算起年龄
属性。
这样:
public DateTime DateOfBirth { get ; set ; }
public int 年龄
{
< span class =code-keyword> get { return (DateTime.Today - DateOfBirth).Days / 365 跨度>; }
}
分析:
-(DateTime.Today - DateOfBirth)
返回TimeSpan
值。
- TimeSpan中的总天数除以一年中的平均天数年龄的近似值。
请注意,Age属性是只读的,因为每次调用属性getter时都会计算它。因此它总是返回当前年龄。
希望这会有所帮助。麻烦。
Hi,
I was trying to figure out how could I do something if age is between, for example 16-21.
What I have tried:
I have a class called Person.
public string Name { get; set; }
public string Surname { get; set; }
public DateTime Age { get; set; }
}
I was trying to figure out to determine the age between certain values. So let's say that:
Person:
Name: Blah
Surname: Nah
Age: 20
I was trying to create an if statement saying
if age is between 16 and 21 do something etc.
How could I do that?
Thanks in advance.
Have a look here: Working with Age: it's not the same as a TimeSpan![^]
Actually, you should not have anAge
DateTime property. It should be namedDateOfBirth
(for example). TheAge
property can then be computed when you need it, from the date of birth.
This way:
public DateTime DateOfBirth { get; set; } public int Age { get { return (DateTime.Today - DateOfBirth).Days / 365; } }
Analyze:
-(DateTime.Today - DateOfBirth)
returns aTimeSpan
value.
- The total number of days in the TimeSpan is divided by the average number of days in a year to give an approximation of the age.
Note that the Age property is read-only, as it is computed everytime the property getter is called. It thus always returns the current age.
Hope this helps. Kindly.
这篇关于使用日期时间计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!