C analysis of accurate age calculation methods

  • 2021-01-06 00:42:57
  • OfStack

This article illustrates an C# method for calculating age accurately. Share to everybody for everybody reference. The details are as follows:

The source code in vs2010 test passed

using System;
using System.Collections.Generic;
using System.Text;
namespace PublicClass
{
    public static class CalculationDate
    {
        /// <summary>
        /// Age is calculated from two dates ( Year, month, day )
        /// </summary>
        public static void calculationDate(DateTime beginDateTime, DateTime endDateTime)
        {
            if (beginDateTime > endDateTime)
                throw new Exception(" The start time should be less than or equal to the end time! ");
            /* Count the total number of months from birth date to current date */
            int Months = endDateTime.Month - beginDateTime.Month + 12 * (endDateTime.Year - beginDateTime.Year);
            /* Date of birth added to the number of months, if greater than the current date is subtracted 1 months */
            int totalMonth = (beginDateTime.AddMonths(Months) > endDateTime) ? Months - 1 : Months;
            /* Calculate the whole year */
            int fullYear = totalMonth / 12;
            /* Calculate a whole month */
            int fullMonth = totalMonth % 12;
            /* Calculate number of days */
            DateTime changeDate = beginDateTime.AddMonths(totalMonth);
            double days = (endDateTime - changeDate).TotalDays;
        }
    }
}

I hope this article is helpful to your C# programming.


Related articles: