计算两个日期之间的差异并获得以年为单位的值?
可能的重复:
如何在 C# 中计算某人的年龄?
我想基本上计算员工的年龄 - 所以我们有每个员工的出生日期,依此类推 在 C# 方面,我想做这样的事情 -
int age=Convert.Int32(DateTime.Now-DOB);
我可以使用天数并进行操作,然后获取年龄...但我想知道是否有一些东西可以直接使用来获取年数。
Possible Duplicate:
How do I calculate someone’s age in C#?
I want to calculate basically the age of employees - So we have DOB for each employee, So on
the C# Side I want to do something like this -
int age=Convert.Int32(DateTime.Now-DOB);
I can use days and manipulate then get the age...but I wanted to know if there something I can use directly to get the number of years.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您想计算员工的年龄吗?然后您可以使用此代码段(来自 Calculate Age in C# ):
如果没有,请具体说明。我很难理解你想要什么。
Do you want calculate the age in years for an employee? Then you can use this snippet (from Calculate age in C#):
If not, then please specify. I'm having a hard time understanding what you want.
减去两个
DateTime
得到一个TimeSpan
回来。不幸的是,它返回的最大单位是天。虽然不准确,但您可以估计它,如下所示:
编辑:哎呀,TotalDays 是一个双精度数,Days 是一个 int。
Subtracting two
DateTime
gives you aTimeSpan
back. Unfortunately, the largest unit it gives you back is Days.While not exact, you can estimate it, like this:
Edit: Whoops, TotalDays is a double, Days is an int.
在此网站上,他们有:
On this site they have:
Math.Round(DateTime.Now.Subtract(DOB).TotalDays/365.0)
正如所指出的,这是行不通的。您必须这样做:
此时另一个解决方案不太复杂,并且在更大的跨度上仍然准确。
编辑2,怎么样:
天哪,我这些天基础数学很糟糕......
Math.Round(DateTime.Now.Subtract(DOB).TotalDays/365.0)
As pointed out, this won't work. You'd have to do this:
and at that point the other solution is less complex and continues to be accurate over larger spans.
Edit 2, how about:
Christ I suck at basic math these days...
从另一个 DateTime 结构中减去 DateTime 结构将得到一个具有 TotalDays 属性的 TimeSpan 结构...然后除以 365
Subtracting a DateTime struct from another DateTime struct will give you a TimeSpan struct which has the property TotalDays... then just divide by 365