将D.O.B转换为Age [英] Convert D.O.B into Age
本文介绍了将D.O.B转换为Age的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好.
我正在做一个c#桌面应用程序,并试图将出生日期"转换为年龄".
问题是我从SQL SERVER 2008服务器检索出生日期"为nvarchar,并将其保存为C#作为字符串.
有帮助吗?
Hi there.
Im doing a c# desktop application and trying to convert a "Date Of Birth" into an "Age".
Problem is that I retrieve the "Date Of Birth" from an SQL SERVER 2008 server as a nvarchar and save it in C# as a string.
Any help?
推荐答案
尝试一下:
Try this:
String dob = "2010/01/01";//read from your database to get dob, just an example
DateTime dateOfBirth = DateTime.Parse( dob );
Int32 age = DateTime.Now.Year - dateOfBirth.Year;
//age=1 in above code
祝你好运
Good luck
尝试
public static int GetAge(string strDate)
{
DateTime birthDate = DateTime.Parse(strDate);
DateTime n = DateTime.Now;
int age = DateTime.Now.Year - birthDate.Year;
if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
age--;
return age;
}
或作为扩展方法:
Or as an extension method:
public static class ExtensionMethods
{
public static int Age(this DateTime dt)
{
TimeSpan span = DateTime.Now.Date - dt.Date;
return Math.Min(1, span.TotalDays % 365);
}
}
这篇关于将D.O.B转换为Age的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文