C#格式化年龄 – 关于天,周,月 – 年

前端之家收集整理的这篇文章主要介绍了C#格式化年龄 – 关于天,周,月 – 年前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在研究一些医疗软件,我需要根据以下规则以非常具体的方式输出所有年龄段:
If under 6 Weeks old :  ###D (Number of Days)
If under 6 Months old :  ###W (Number of Weeks)
 If under 2 Years old :  ###M (Number of Months)
 If above 2 Years old :  ###Y (Number of Years)

使用C#我试图找到一个简单的方法,只使用一个人的出生日期,任何帮助将不胜感激.

解决方法

我昨天正在做类似的事情,但这样的事情应该适合你的需要:(假设7天,31天,365天等)

修订方法:(根据鲍勃的建议修正)

public static string ConvertAge(DateTime dob)
    {
        DateTime today = DateTime.Today;
        string fmt = "{0:0##}{1}";

        //Greater than 2 Years old - Ouput Years
        if (dob <= today.AddYears(-2)) 
            return string.Format(fmt,(dob.DayOfYear <= today.DayOfYear) ? 
            (today.Year - dob.Year) : (today.Year - dob.Year)-1,"Y");
        //Less than 2 Years - Output Months
        if (dob < today.AddMonths(-2)) 
            return string.Format(fmt,(dob.DayOfYear <= today.DayOfYear) ? 
            (today.Year - dob.Year) * 12 + (today.Month - dob.Month) : 
            ((today.Year - dob.Year) * 12 + (today.Month - dob.Month))-1,"M");
        //Less than 2 Months - Output Weeks
        if (dob < today.AddDays(-2 * 7)) 
            return string.Format(fmt,(today - dob).Days / 7,"W");
        //Less than 2 Weeks - Output Days
        return string.Format(fmt,(today - dob).Days,"D");
    }

上一种方法

public string ConvertAge(DateTime dateOfBirth)
        {
            int daysOld = (DateTime.Now - dateOfBirth).Days;

            //Age < 6 Weeks
            if (daysOld < (6 * 7)) 
                return String.Format("{0:0##}{1}",daysOld,'D'); 
            //Age < 6 Months
            else if (daysOld < (6 * 31)) 
                return String.Format("{0:0##}{1}",daysOld/7,'W');
            //Age < 2 Years
            else if (daysOld < (2 * 365)) 
                return String.Format("{0:0##}{1}",daysOld / 31,'M');
            //Age >= 2 Years
            else 
                return String.Format("{0:0##}{1}",daysOld / 365,'Y');
        }

希望这可以帮助!

原文链接:/csharp/99892.html

猜你在找的C#相关文章