当前位置: 移动技术网 > IT编程>开发语言>c# > C#实现计算年龄的简单方法汇总

C#实现计算年龄的简单方法汇总

2019年07月18日  | 移动技术网IT编程  | 我要评论

vs2010测试通过,主要思想是由出生日期和当前日期,两个日期计算出年龄(岁、月、天)

using system;
using system.collections.generic;
using system.text;
 
namespace publicclass
{
  public static class calculationdate
  {
    /// <summary>
    /// 由两个日期计算出年龄(岁、月、天)
    /// </summary>
    public static void calculationdate(datetime begindatetime, datetime enddatetime)
    {
      if (begindatetime > enddatetime)
        throw new exception("开始时间应小于或等与结束时间!");
 
      /*计算出生日期到当前日期总月数*/
      int months = enddatetime.month - begindatetime.month + 12 * (enddatetime.year - begindatetime.year);
      /*出生日期加总月数后,如果大于当前日期则减一个月*/
      int totalmonth = (begindatetime.addmonths(months) > enddatetime) ? months - 1 : months;
      /*计算整年*/
      int fullyear = totalmonth / 12;
      /*计算整月*/
      int fullmonth = totalmonth % 12;
      /*计算天数*/
      datetime changedate = begindatetime.addmonths(totalmonth);
      double days = (enddatetime - changedate).totaldays;
    }
  }
}

再简单一些:

public int calculateagecorrect(datetime birthdate, datetime now)
{
  int age = now.year - birthdate.year;
  if (now.month < birthdate.month || (now.month == birthdate.month && now.day < birthdate.day)) age--;
  return age;
}

下面我们来看看常规方法:

方法1:

    string m_str = "1984-04-04";
    int m_y1 = datetime.parse(m_str).year;
    int m_y2 = datetime.now.year;
    int m_age = m_y2 - m_y1;
    response.write(m_age);

方法2:

      如果你将日期格式化为yyyymmdd,并且从当前日子减去生日,最后去除4个数字,就得到年龄了:)
      我相信这样的方法可以用任何语言实现:

     20080814-19800703=280111

     去除最后4位 = 28.

 

  int now =int.parse(datetime.today.tostring("yyyymmdd"));

  int dob =int.parse(datedob.tostring("yyyymmdd"));

  string dif =(now - dob).tostring();

  string age ="0";

  if(dif.length>4)
    age = dif.substring(0, dif.length-4);


方法3:

datetime now =datetime.today;

int age = now.year- bday.year;

if(bday > now.addyears(-age)) age--;

以上所述就是本文的全部内容了,希望能对大家学习c#有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网