Convert TimeSpan to Days and Hours in C# .Net

Last Reply on Sep 09, 2014 02:32 AM By Azim

Posted on Sep 08, 2014 04:32 AM

 

 string constr = ConfigurationManager.AppSettings["s"].ToString();
        using (SqlConnection conn = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT CONVERT(VARCHAR(10),InTime,108 ), CONVERT(VARCHAR(10),outTime,108 ) FROM aten WHERE Id = '" + txtid.Text + "'", conn))
            {
                conn.Open();
                SqlDataReader sdr = cmd.ExecuteReader();
                TimeSpan i = new TimeSpan(0, 0, 0);
                while (sdr.Read())
                {
                    DateTime inTime = Convert.ToDateTime(sdr[0].ToString(), new CultureInfo("en-Gb"));
                    DateTime outTime = Convert.ToDateTime(sdr[1].ToString(), new CultureInfo("en-Gb"));
                    i += outTime.Subtract(inTime);
                }
                this.txthourswrk.Text = i.ToString();
                conn.Close();
             }
        }

using the code i got the result as 1day 1 hour 23 minutes and 22seconds . i  need as 1 day as 24 hours in asp.net

You are viewing reply posted by: Azim on Sep 09, 2014 02:32 AM.
Posted on Sep 09, 2014 02:32 AM

Please consider this example

TimeSpan timeSpan = new TimeSpan();
DateTime dtStart = DateTime.Now;
DateTime dtEnd = DateTime.Now.AddHours(1.5).AddDays(1);
timeSpan = dtEnd.Subtract(dtStart);
double hours = timeSpan.Hours + (timeSpan.Days * 24);
string time = string.Format("{0}hours and {1}minutes", hours, timeSpan.Minutes);

You can find the total hour as below code.

double hours = timeSpan.Hours + (timeSpan.Days * 24);

And this will also give you total hours

int totalHours = (int)timeSpan.TotalHours;

This will suppress the minutes and give you only hours.