question

HemanthB-9452 avatar image
0 Votes"
HemanthB-9452 asked HemanthB-9452 commented

Age Calculator C#

Hi, this an age calculator:
private void button1_Click(object sender, EventArgs e)
{
try
{
if (dtpcurrentdate.Value < dtpdateofbirth.Value)
{

                     System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\Windows\Media\Windows Foreground.wav");
                     player.Play();
                        
                     MessageBox.Show("Error Calculating! The Date of Birth is greater than the Current Date. Please Try Again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                     lblyears.Text = "";
                     lblmonths.Text = "";
                        
                 }
                 else if (dtpcurrentdate.Value < dtpdateofbirth.Value)
                 {
                     lblyears.Text = "";
                     lblmonths.Text = "";
                 }
    
    
    
    
    
    
                 int Age = dtpcurrentdate.Value.Year - dtpdateofbirth.Value.Year;
                 //if add Dateofbirth+Age <Current Age 
                 Age--;
                 int AgeinMonths = dtpcurrentdate.Value.Month - dtpdateofbirth.Value.Month;
                 int ageindays = dtpcurrentdate.Value.Day - dtpdateofbirth.Value.Day;
                 if (dtpcurrentdate.Value > dtpdateofbirth.Value)
                 {
                     lblyears.Text = Age.ToString() + " Year(s) " + AgeinMonths.ToString() + " Month(s)" + ageindays.ToString() + " Day(s)";
                        
                 }
             }

But the problem is it shows some values in negative. For example if select Date of birth date time picker as 7th October 2008 and then select today's date (17th july 2021) in the current date dtp, then it shows the result as: 12 years, -3 months, 10 days. I want it to show 9 months instead of -3 months.

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered HemanthB-9452 commented

Give the following a try (full source).

  • You can add your assertion to ensure the before date is less than the current date.

    using System;

    namespace TimeLibrary.Classes
    {
    public static class Helpers
    {

           /// <summary>
             /// Get elapsed time in years, months, days, hours, seconds
             /// </summary>
             /// <param name="fromDate">Date in past</param>
             /// <param name="toDate">Date pass fromDate</param>
             /// <param name="years"></param>
             /// <param name="months"></param>
             /// <param name="days"></param>
             /// <param name="hours"></param>
             /// <param name="minutes"></param>
             /// <param name="seconds"></param>
             /// <param name="milliseconds"></param>
             public static void GetElapsedTime(this DateTime fromDate, DateTime toDate, out int years, out int months, out int days, out int hours, out int minutes, out int seconds, out int milliseconds)
             {
                 // If from_date > to_date, switch them around.
                 if (fromDate > toDate)
                 {
                     GetElapsedTime(
                         toDate, 
                         fromDate, 
                         out years, 
                         out months, 
                         out days, 
                         out hours, 
                         out minutes, 
                         out seconds, 
                         out milliseconds);
                        
                     years = -years;
                     months = -months;
                     days = -days;
                     hours = -hours;
                     minutes = -minutes;
                     seconds = -seconds;
                     milliseconds = -milliseconds;
                 }
                 else
                 {
                     // Handle the years.
                     years = toDate.Year - fromDate.Year;
        
                     // See if we went too far.
                     DateTime testDate = fromDate.AddMonths(12 * years);
                     if (testDate > toDate)
                     {
                         years--;
                         testDate = fromDate.AddMonths(12 * years);
                     }
        
                     // Add months until we go too far.
                     months = 0;
                     while (testDate <= toDate)
                     {
                         months++;
                         testDate = fromDate.AddMonths(12 * years + months);
                     }
        
                     months--;
        
                     // Subtract to see how many more days,
                     // hours, minutes, etc. we need.
                     fromDate = fromDate.AddMonths(12 * years + months);
                     TimeSpan remainder = toDate - fromDate;
                     days = remainder.Days;
                     hours = remainder.Hours;
                     minutes = remainder.Minutes;
                     seconds = remainder.Seconds;
                     milliseconds = remainder.Milliseconds;
                        
                 }
             }
         }
     }
    

Usage (using a console app to keep things clear)

 using System;
 using TimeLibrary.Classes;
    
 namespace TimeLibraryConsoleApp
 {
     class Program
     {
         static void Main(string[] args)
         {
             var fromDateTime = new DateTime(2008, 9, 24);
             var toDateTime = DateTime.Now;
    
             fromDateTime.GetElapsedTime(toDateTime, 
                 out var years, out var months, out var days,
                 out var hours, out var minutes, out var seconds, 
                 out _);
    
             Console.WriteLine($"Age is {years} years {months} months {days} days");
             Console.ReadLine();
         }
     }
 }

115585-figure1.png




figure1.png (8.4 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks so much, it works!

0 Votes 0 ·