C#判断生日是否已经过去6个月
如果距客户上次生日已过去 6 个月,我的应用程序需要将客户当前年龄调整 +0.5。
代码应该看起来像这样,但是 6 个月内会有多少个刻度?
if (DateTime.Today - dateOfBirth.Date > new TimeSpan(6))
{
adjust = 0.5M;
}
else
{
adjust = 0M;
}
提前致谢
My application needs to adjust a clients current age by +0.5 if it has been 6 months since their last birthday.
The code should look something like this, but how many ticks would there be in 6 months?
if (DateTime.Today - dateOfBirth.Date > new TimeSpan(6))
{
adjust = 0.5M;
}
else
{
adjust = 0M;
}
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
编辑:你实际上知道吗?由于显然您真正需要的只是显示 6 个月以内的用户年龄,因此这才是您真正应该做的。
上面的代码包含一个大注释,解释了它自己的缺点,大卫指出了这一点。
现在,还有另一个选项。它有点丑陋,因为它使用了循环;但它也更加坚如磐石,因为它使用了 DateTime.AddMonths 方法,该方法的优点是已经过 Microsoft 的测试和记录。
人们一直建议检查
dateOfBirth.AddMonths(6)
的想法是错误。由于dateOfBirth
是一个 DateTime,因此它表示用户的出生日期,而不是他们的出生日期。您要检查的是自用户的最后生日(而不是他们的出生日期)以来是否已经过去了六个月。这是一种方法:
EDIT: You know what, actually? Since clearly what you really need is just to display the user's age to within 6 months, this is what you should really do.
The above code includes a big comment explaining its own shortcomings, helpfully pointed out by David.
Now, here's yet another option. It's kind of ugly because it uses a loop; but it's also more rock-solid since it utilizes the DateTime.AddMonths method, which has the advantage of having already been tested and documented by Microsoft.
This idea that people have been suggesting of checking
dateOfBirth.AddMonths(6)
is wrong. SincedateOfBirth
is a DateTime, it represents the user's birth date, not their birth day.What you want to check is if six months have elapsed since the user's last birthday--not the date they were born. Here's one way to do that:
为什么不改为
if (dateOfBirth.Date.AddMonths(6) < DateTime.Today)
呢?Why not
if (dateOfBirth.Date.AddMonths(6) < DateTime.Today)
instead?我认为你可能把事情过于复杂化了:
I think you might be overcomplicating things:
像这样的东西吗?
Something like this?
我想你实际上想知道距离他们上次生日是半年还是六个月(因为几个月的长度各不相同)。
I think you actually want to know if it is half a year since their last birthday not six months (since months vary in length).