使用日期时间计算年龄

编程入门 行业动态 更新时间:2024-10-27 22:27:02
本文介绍了使用日期时间计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图找出如果年龄介于两者之间我该怎么办,例如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 年龄 { 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 an Age DateTime property. It should be named DateOfBirth (for example). The Age 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 a TimeSpan 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.

更多推荐

使用日期时间计算年龄

本文发布于:2023-10-18 11:44:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504138.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:年龄   日期   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!