C#精确计算时代 [英] C# calculate accurate age

查看:93
本文介绍了C#精确计算时代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道如何根据日期(生日)获取年龄



大概是这样即时通讯思想

 串年龄= DateTime.Now.GetAccurateAge(); 

和输出会像20年5个月20天的一些东西。


解决方案

 公共静态类DateTimeExtensions 
{
公共静态字符串ToAgeString(这个日期DOB)
{$今天b $ b =的DateTime DateTime.Today;

INT个月= today.Month - dob.Month;
INT年= today.Year - dob.Year;

如果(today.Day< dob.Day)
{
months--;
}

如果(月℃,)
{
years--;
+月= 12;
}

INT天数=(今 - dob.AddMonths((*年12)+月))天。

返回的String.Format({0}年{1},{2}月{3}和{4}天{5},
岁,(岁== 1 ),:S,
月,(月== 1)?:S,
天(天== 1),:?的);
}
}


anyone know how to get the age based on a date(birthdate)

im thinking of something like this

string age = DateTime.Now.GetAccurateAge();

and the output will be some thing like 20Years 5Months 20Days

解决方案

public static class DateTimeExtensions
{
    public static string ToAgeString(this DateTime dob)
    {
        DateTime today = DateTime.Today;

        int months = today.Month - dob.Month;
        int years = today.Year - dob.Year;

        if (today.Day < dob.Day)
        {
            months--;
        }

        if (months < 0)
        {
            years--;
            months += 12;
        }

        int days = (today - dob.AddMonths((years * 12) + months)).Days;

        return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
                             years, (years == 1) ? "" : "s",
                             months, (months == 1) ? "" : "s",
                             days, (days == 1) ? "" : "s");
    }
}

这篇关于C#精确计算时代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆