zoukankan      html  css  js  c++  java
  • C# 根据出生年月 计算天数/计算X岁X月X天字符串

    public class TimeTool
        {
            //根据出生年月计算 整数天
            private static int GetAgeByBirthdate(DateTime birthdate)
            {
                DateTime now = DateTime.Now;
                int age = now.Year - birthdate.Year;
                if (now.Month < birthdate.Month || (now.Month == birthdate.Month && now.Day < birthdate.Day))
                {
                    age--;
                }
                return age < 0 ? 0 : age;
            }           //根据出生年月计算 X岁或X月X天或X天
            public static string GetAgeByBirthday(DateTime birthday)
            {
                var currenttime = DateTime.Now;
                var diffTime = currenttime - birthday;
                if (diffTime.TotalDays >= 365)
                {
                    //年龄计算
                    return GetAgeByBirthdate(birthday).ToString() + "岁";
                }
                else
                {
                    //个月计算
                    var diffmonth = currenttime.Month - birthday.Month;
                    var day = currenttime.Day - birthday.Day;
                    if (day < 0)
                    {
                        diffmonth--;
                    }
                    if (diffmonth > 0)
                    {
                        DateTime newbirthday = birthday.AddMonths(diffmonth);
                        day = (int)((currenttime - newbirthday).TotalDays);
                        return diffmonth.ToString() + "个月" + (day == 0 ? "" : day.ToString() + "天");
                    }
                    else
                    {
                        //直接计算天
                        return ((int)(diffTime.TotalDays)).ToString() + "天";
                    }
                }
    
            }
        }
    

      

  • 相关阅读:
    Hibernate----面试题
    Java框架部分---面试题
    面试题---多线程
    swap分区
    Linux之格式化与挂载
    Linux下的GPT分区
    Linux下的MBR分区
    vim基础初步
    管道符,通配符以及其他特殊符号
    shell基础之脚本执行,命令别名以及快捷键等
  • 原文地址:https://www.cnblogs.com/DoNetCShap/p/13707221.html
Copyright © 2011-2022 走看看