C# calculate accurate age

前端 未结 14 1796
攒了一身酷
攒了一身酷 2020-12-15 11:01

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

im thinking of something like this

string age = DateTime.Now.GetAccurateAge();
14条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 11:44

    @if (Model.CF_DateOfBirth.HasValue)
                                            {
                                                var today = DateTime.Today;
                                                var months = DateTime.Today;
                                                var age = today.Year - Model.CF_DateOfBirth.Value.Year;
                                                var mons = months.Month - Model.CF_DateOfBirth.Val`enter code here`ue.Month;
                                                if (Model.CF_DateOfBirth > today.AddYears(-age) && Model.CF_DateOfBirth>months.AddMonths(-mons))
                                                {
                                                    age--; mons--;
                                                }
                                                  Date of birth:  @Convert.ToDateTime(Model.CF_DateOfBirth).ToShortDateString().ToString()   ( @ageYears  @mons Months)
    
                                            }
    

提交回复
热议问题