Skip to content

Calcalute hours between two date using timespan

durga prasad

Asked Aug 9, 2008, 12:11 AM EDT1 answer
Share
LinkedInX
Hi,
How calcalute total working hours between two date using timespan/date time pickers.

My code looks something like this, I am able to calculate for today but when the employee works for extra hours, for example he come today at 5pm and leaves by 5am in the next day, then how do i calculate?
                TimeSpan ts = new TimeSpan();
                ts = dtpouttime.Value.TimeOfDay - tpintime.Value.TimeOfDay;
                ts = ts.Subtract(TimeSpan.FromMinutes(30));

                if (ts.TotalHours <= 8.30)
                {
txtworkedhours.Text = Convert.ToDecimal(ts.TotalHours).ToString("#0.00");

                    txtextrahours.Text = "";
                    //calc2.Text = calc1.Text;

                    calc1.Text = ts.ToString();
                }

else if (ts.TotalHours >= 8.31)
                {
                    calc1.Text = "";
                    calc2.Text = "";

                    txtextrahours.Text = "";
                    txtworkedhours.Text = "";

                    TimeSpan ts4 = new TimeSpan(8, 30, 0);
                    txtworkedhours.Text = (Convert.ToDecimal(Convert.ToDecimal(ts4.TotalHours)).ToString("#0.00"));
                    calc1.Text = ts4.ToString();


                    TimeSpan ts3 = new TimeSpan
                ts3 = ts.Subtract(TimeSpan.FromHours(9) - (TimeSpan.FromMinutes(30)));
    txtextrahours.Text = Convert.ToDecimal(ts3.TotalHours).ToString("#0.00");
                    calc2.Text = ts3.ToString();


                }

                else
                {
                    MessageBox.Show("Invalid input");
                }





Thanks in Advance,
A.Durga Prasad

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
                TimeSpan ts = dateTimePicker2.Value - dateTimePicker1.Value;
                label1.Text = ts.Days.ToString() + ":" + ts.Hours.ToString() + ":" + ts.Minutes.ToString() + ":" + ts.Seconds.ToString();

    this should do it. You must use the Days * 24 if you want to get the total hours working
    0