Basic simple age calculator for date of birth in C #

I created a simple age calculator. I want to remove the decimal places, but the problem is what I am putting now

in bday

.

example : i was typing 2012

, 10

and 23

and now the date 2014-10-22

, so when the 2014.1022 - 2012.1023

result is 1.9999...

, i want to remove all decimals and remain an integer 1

, but the time i am using String.Format("{0:00}"

rounds the result to 02

, even when i use ConvertToInt32

i dont want to use split string , it needs a lot of code.

Any ideas?

 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();

                 }
                 Console.WriteLine("Your Age is " + (String.Format("{0:00}", (now - bday)))); //it rounds off my float
                 Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }

        }

      

}

+3


source to share


3 answers


Here I found the answer to my own question, I am using LastIndexOf

to delete the whole line after a certain character which is a dot (.), But before that I am converted float

to string

.

That's for sure, 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();
        }





        }

      

-1


source


Unlike the comments, TimeSpan

won't help you here because the year is not a fixed period of time. This, in turn, makes your expressed purpose very strange. You really don't have to represent a date as a fractional number, with the first two digits representing months and the third and fourth digits representing days. Time just doesn't work. (Consider that the difference between 2014.0131 and 2014.0201 is much larger than the difference between 2014.0130 and 2014.0131, for example.)

It would be better to represent age in terms of years, months, and days. My Noda Time library makes it 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 just want to define a few years, you can just use, period.Years

or perhaps round the result based on period.Months

.

I would recommend not using DateTime.Now

in production code. In Noda Time, we have an interface IClock

representing a "way to get the current point in time", implemented SystemClock

in the main assembly and implemented FakeClock

in the test assembly. Your code will take IClock

(possibly via dependency injection) and then use it to determine the current date in whatever timezone you are interested in. This way, you can write tests for any situation you like without changing your computer clock. This is a good way to handle time-related tasks in general IMO.

+9


source


Within our framework, we use the following methods:

    /// <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);
    }

      

+2


source







All Articles