Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a timespan to show me total hours?

Tags:

I want to save the user's hours worked in a database varchar column, but by default, the formatted value includes days if the number of hours is more than 24. I just want the total number of hours.

For example: if a user works 10:00:00 hours today, then 13:00:00 hours tomorrow, and 3:30:00 hours the day after tomorrow then the formatted total I want is 26:30:00. Instead, I am seeing 1.2:30:00.

How can I get the formatting I want?

Also, when I save the value 40:00:00 in the database manually, and try to read it into a TimeSpan later, I get a bug.

How can I save the hours in the database the way I want, and still be able to read it back into a TimeSpan later?

like image 745
angel Avatar asked May 20 '11 15:05

angel


People also ask

What is TimeSpan format?

A TimeSpan format string defines the string representation of a TimeSpan value that results from a formatting operation. A custom format string consists of one or more custom TimeSpan format specifiers along with any number of literal characters.

What is time span in C#?

C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.


2 Answers

You could do something like:

TimeSpan time = ...; string timeForDisplay = (int)time.TotalHours + time.ToString(@"\:mm\:ss"); 
like image 161
CodingWithSpike Avatar answered Sep 17 '22 16:09

CodingWithSpike


Try TimeSpan.TotalHours

String timeStamp = "40:00:00"; var segments = timeStamp.Split(':');  TimeSpan t = new TimeSpan(0, Convert.ToInt32(segments[0]),                 Convert.ToInt32(segments[1]), Convert.ToInt32(segments[2])); string time = string.Format("{0}:{1}:{2}",             ((int) t.TotalHours), t.Minutes, t.Seconds); 
like image 40
Bala R Avatar answered Sep 19 '22 16:09

Bala R