How can I calculate the age of a person in year, month, days?

前端 未结 11 1191
谎友^
谎友^ 2020-11-27 05:52

I want to calculate the age of a person given the date of birth and the current date in years, months and days relative to the current date.

For example:

<         


        
11条回答
  •  抹茶落季
    2020-11-27 06:41

    I assume the questions is broader than only one programming language. If you are using C#, you can use DateTimeOffset to calculate this.

    var offset = DateTimeOffset.MinValue;
    var lastDate = DateTime.Today;
    var firstDate = new DateTime(2006,11,19);
    
    
    var diff = (lastDate- firstDate);
    var resultWithOffset = DateTimeOffset.MinValue.AddDays(diff.TotalDays);
    var result = resultWithOffset.AddDays(-offset.Day).AddMonths(-offset.Month).AddYears(-offset.Year);
    

    result.Day, result.Month, result.Year will hold the information you need.

提交回复
热议问题