Fun with DateTime and TimeSpan

ddanbe 0 Tallied Votes 709 Views Share

This is just for fun. You know how old you are(I hope), but do you know how many days you are walking around on this planet?
The two routines presented here could be used more practically in an ever present employee application.

using System;

namespace DateFun
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the current date time settings from the computer
            DateTime currentDay = DateTime.Now;

            // Fill in a birthday
            // In a form application use a DateTimePicker.
            // Here normally use ReadLine, I used inits to keep it simple
            int year = 1952;
            int month = 1;
            int day = 18;
            DateTime birthDay = new DateTime(year, month, day);

            Console.WriteLine("Fun with DateTime and TimeSpan!");
            Console.WriteLine();

            // Calculate and display an age
            int yourAge = AgeCalculation(currentDay, birthDay);
            Console.WriteLine("You are {0} years old (or young!).", yourAge);

            // Calculate the total amount of days you are living on this planet
            string daysAlive = DaysAliveCalculation(ref currentDay, ref birthDay);
            Console.WriteLine("You are {0} days alive and kicking!", daysAlive);
            
            Console.ReadKey();
        }

        private static string DaysAliveCalculation(ref DateTime currentDay, ref DateTime birthDay)
        {
            // Calculate the differnece in ticks
            long DifTicks = currentDay.Ticks - birthDay.Ticks;
            // Make a TimeSpan object out of it
            TimeSpan TS = new TimeSpan(DifTicks);
            // Extract the days out of it as a string
            string daysAlive = TS.Days.ToString();
            return daysAlive;
        }

        private static int AgeCalculation(DateTime curDate, DateTime birthDate)
        {
            DateTime testDate = new DateTime(curDate.Year, birthDate.Month, birthDate.Day);
            int Age = curDate.Year - birthDate.Year;
            // Overloaded comparision operator
            if (testDate <= curDate) // You do not yet celebrate your birthday this year
            {
                Age--;
            }
            return Age;
        }
    }
}
subtercosm 0 Light Poster

Why are you passing the DateTimes by reference to DaysAliveCalculation? I can't see any reason for this.

Also, DaysAliveCalculation would be much more reusable if it returned an int. By returning a string, you're suggesting that the function is returning something sneaky.

ddanbe 2,724 Professional Procrastinator Featured Poster

I indeed don't have to pass by reference here. Just pointing out you could. You're absolutly right with your second remark. Something that is meant to return a number, should return a number!
On the other hand this was not something meant to be carved in stone. Feel free to change whatever you like.
Thanks for your remarks.

anmoldeep 0 Newbie Poster

my version:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication19
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        long startdate1, startmonth1, startyear1, enddate1, endmonth1, endyear1;


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                startdate1 = long.Parse(startdate.Text);

                startmonth1 = int.Parse(startmonth.Text);
                startyear1 = long.Parse(startyear.Text);

                enddate1 = long.Parse(enddate.Text);
                endmonth1 = long.Parse(endmonth.Text);
                endyear1 = long.Parse(endyear.Text);
                textBox9.Text = Convert.ToString((endyear1 - startyear1)); //printing the year between the dates
                long numberofdaysinstartyear = 0, counter2 = 0;
                for (long i = startmonth1 + 1; i <= 12; i++)
                {

                    long xx = DateTime.DaysInMonth(Convert.ToInt16(startyear1), Convert.ToInt16(i));
                    numberofdaysinstartyear += xx;

                }
                long yy = DateTime.DaysInMonth(Convert.ToInt16(startyear1), Convert.ToInt16(startmonth1));
                numberofdaysinstartyear += (yy - startdate1);

                //MessageBox.Show("remaining num of days in start year" + numberofdaysinstartyear.ToString()); // remaining num of days in start year

                for (long j = startyear1 + 1; j < endyear1; j++)
                {
                    for (long k = 1; k <= 12; k++)
                    {

                        long jj = DateTime.DaysInMonth(Convert.ToInt16(j), Convert.ToInt16(k));
                        counter2 += jj;
                    }
                }
                #region leap
                long i2;
                long x2;
                long leapdays = 0;
                for (i2 = 4; i2 <= 2090; i2 += 4)
                {
                    for (x2 = startyear1; x2 <= endyear1; x2 += 1)
                    {
                        if (i2 == x2)
                        {
                            leapdays += 1; // no. of leap days addition if we take all days normal(works)+++
                        }


                    }

                }
                // MessageBox.Show("leap days: " + leapdays.ToString());
                #endregion


                // MessageBox.Show("no. of days in b/w the years : "+counter2.ToString());


                long kk;
                long counter3 = 0;
                for (kk = endmonth1 + 1; kk <= 12; kk++)
                {
                    long yyy;
                    yyy = DateTime.DaysInMonth(Convert.ToInt16(endyear1), Convert.ToInt16(kk));

                    counter3 += yyy;


                }
                long numberofdaysinthat_endmonth = enddate1;
                long alldaysinendmonth = DateTime.DaysInMonth(Convert.ToInt16(endyear1), Convert.ToInt16(endmonth1));
                long numberofrestofdaysinendyear = ((364 - (counter3 + alldaysinendmonth)) + numberofdaysinthat_endmonth) + 1;
                // MessageBox.Show("number of rest of days in end year" + numberofrestofdaysinendyear.ToString());
                long total_days = numberofdaysinstartyear + counter2 + numberofrestofdaysinendyear;

                if (startmonth1 == endmonth1 && startyear1 == endyear1)
                {

                    long dz1 = enddate1 - startdate1;

                    textBox7.Text = Convert.ToString(dz1);
                }


                else
                {
                    if (Convert.ToString(startyear1) != Convert.ToString(endyear1))
                    {
                        textBox7.Text = Convert.ToString(total_days);
                    }
                    else
                    {
                        long numberofdaysinstartyear1 = 0;
                        for (long i = startmonth1 + 1; i < endmonth1; i++)
                        {

                            long xx = DateTime.DaysInMonth(Convert.ToInt16(startyear1), Convert.ToInt16(i));
                            numberofdaysinstartyear1 += xx;
                            // MessageBox.Show(Convert.ToString(numberofdaysinstartyear1));


                        }
                        long numberofdaysinstartyear3;
                        long yyy = DateTime.DaysInMonth(Convert.ToInt16(startyear1), Convert.ToInt16(startmonth1));
                        numberofdaysinstartyear3 = numberofdaysinstartyear1 + (yyy - startdate1) + enddate1;

                        // MessageBox.Show("num of days in same year " + numberofdaysinstartyear3.ToString()); // num of days in same year till end month plus days of start month
                        textBox7.Text = Convert.ToString(numberofdaysinstartyear3);
                    }
                }











                long days = long.Parse(textBox7.Text);
                long counteryear = 0;
                if (days >= 365)
                {



                    while (days > 364)
                    {

                        long remainderdays = days - 365;
                        days = remainderdays;

                        counteryear += 1;
                    }
                }
                long remainderdays2 = days - leapdays;
                // MessageBox.Show("remainder days: " + Convert.ToString(remainderdays2));
                ////////////////




                if (remainderdays2 <= 31)
                {
                    if (remainderdays2 == 31)
                    {
                        textBox3 .Text ="1";  //////////
                    }
                    else if (remainderdays2 < 31)
                    {
                        textBox3.Text = Convert.ToString(days - leapdays);  //////////
                    }
                }
                else if (remainderdays2 > 31)
                {
                    long countermonth = 0;
                    for (int g = 1; g <= 12; g++)
                    {
                        int l = DateTime.DaysInMonth(Convert.ToInt16(counteryear + 1), Convert.ToInt16(g));
                        while (remainderdays2 > l)
                        {

                            long k = remainderdays2 - l;
                            remainderdays2 = k;


                            countermonth += 1;

                        }

                    }

                    // MessageBox.Show("years: " + Convert.ToString(counteryear));
                    // MessageBox.Show("months  :" +Convert.ToString(countermonth));
                    // MessageBox.Show("final days  :" + Convert.ToString(remainderdays2 ));

                    textBox1.Text = Convert.ToString(counteryear);
                    textBox2.Text = Convert.ToString(countermonth);
                    textBox3.Text = Convert.ToString(remainderdays2);
                }
            }


            catch (Exception x)
            {
                MessageBox.Show(x.ToString());
            }
        }


bool chk;
        private void endyear_KeyDown(object sender, KeyEventArgs e)
        {
           // MessageBox.Show(e.KeyCode.ToString());
            int key = Convert.ToInt32(e.KeyCode);
            if ((key >= 47 && key <= 59) || e.KeyCode==Keys.Back)
            {

            }
            else
            {
                chk = false;
            }
        }



        private void endyear_KeyPress_1(object sender, KeyPressEventArgs e)
        {
            if (chk == false)
            {
                e.Handled = true;
                chk = true;
            }
        }

        private void button1_MouseHover(object sender, EventArgs e)
        {
            this.BackgroundImage = global::WindowsFormsApplication19.Properties.Resources.Vectorious_Wallpaper_Ver_ ;
        }

        private void button1_MouseLeave(object sender, EventArgs e)
        {
            this.BackgroundImage = global::WindowsFormsApplication19.Properties.Resources.Untitled;
        }

        private void startmonth_TextChanged(object sender, EventArgs e)
        {

        }





        }
    }
ddanbe 2,724 Professional Procrastinator Featured Poster

Oops, line 50 of my code should read if (testDate > curDate) instead of if (testDate <= curDate)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.