Simple Age Calculator base on date of birth in C#

This question already has an answer here:

  • How do I calculate someone's age in C#? 64 answers

  • Contrary to the comments, TimeSpan does not help you here, because a year is not a fixed length of time. That in turn leads to your expressed aim being very strange indeed. You really shouldn't be representing a date as a fractional number with the first two digits being months and the third and fourth digits being days. Time just doesn't work like that. (Consider that the difference between 2014.0131 and 2014.0201 is much greater than the difference between 2014.0130 and 2014.0131, for example.)

    It would be better to represent an age in terms of years, months and days. My Noda Time library makes that pretty simple:

    LocalDate birthday = new LocalDate(1976, 6, 19); // For example
    LocalDate today = LocalDateTime.FromDateTime(DateTime.Now).Date; // See below
    Period period = Period.Between(birthday, today);
    Console.WriteLine("You are {0} years, {1} months, {2} days old",
                      period.Years, period.Months, period.Days);
    

    If you want to just determine a number of years, you could decide to just use period.Years , or possibly round the result based on period.Months as well.

    I would recommend against using DateTime.Now in production code, however. In Noda Time, we have an IClock interface representing "a means of getting the current instant in time", with a SystemClock implementation in the main assembly and a FakeClock implementation in the testing assembly. Your code would accept an IClock (possibly with dependency injection) and then use that to determine the current date in whatever time zone you're interested in. That way, you can write tests for any situation you like, without changing your computer's clock. This is a good way of handling time-related tasks in general, IMO.


    在我们的框架中,我们使用以下方法:

        /// <summary>
        /// Calculates the age at the specified date.
        /// </summary>
        /// <param name="dateOfBirth">The date of birth.</param>
        /// <param name="referenceDate">The date for which the age should be calculated.</param>
        /// <returns></returns>
        public static int Age(DateTime dateOfBirth, DateTime referenceDate)
        {
            int years = referenceDate.Year - dateOfBirth.Year;
            dateOfBirth = dateOfBirth.AddYears(years);
            if (dateOfBirth.Date > referenceDate.Date)
                years--;
            return years;
        }
    
        /// <summary>
        /// Calculates the age at this moment.
        /// </summary>
        /// <param name="dateOfBirth">The date of birth.</param>
        /// <returns></returns>
        public static int Age(DateTime dateOfBirth)
        {
            return Age(dateOfBirth, DateTime.Today);
        }
    

    Here I found an answer to my question, I use LastIndexOf to remove all string after a certain character which is point(.), but before that I converted float to string .

    It is accurate, try it. :)

       static void Main(string[] args)
        {
            string year, month, day = string.Empty;
            Console.WriteLine("Enter your Birthdate:");
            Console.WriteLine("Year :");
            year = Console.ReadLine();
            Console.WriteLine("Month :");
             month = Console.ReadLine();
            Console.WriteLine("Day :" );
            day = Console.ReadLine();
            try
            {
                DateTime date = Convert.ToDateTime(year + "-" + month + "-" + day);
                 var bday = float.Parse(date.ToString("yyyy.MMdd"));
                 var now = float.Parse(DateTime.Now.ToString("yyyy.MMdd"));
                 if (now < bday)
                 {
                     Console.WriteLine("Invalid Input of date");
                     Console.ReadLine();
    
                 }
                 string age = (now - bday).ToString(); 
                 Console.WriteLine("Your Age is " + (age.Substring(0, age.LastIndexOf('.'))));
                 Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }
    
    
    
    
    
            }
    
    链接地址: http://www.djcxy.com/p/54354.html

    上一篇: 我怎么能通过datetimepicker计算年龄

    下一篇: 简单年龄计算器基于C#中的出生日期