Home » excel » c# – display a timespan in excel

c# – display a timespan in excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a timespan stored as a varchar in sql in the format of totalhours-totalminutes-totalseconds.
Now I have to export that information into excel.

The problem I’m having is that I can not for the life of me find a format within excel that will display this information correctly. Is there a way in which this information can be displayed correctly? I am using XLS in C# to output this info.

Sample input: 48:00:11

Sample output: 1900/02/17 12:11:00 AM or 48.0076388888889

How to&Answers:

For formatting, you need to set a custom time format:

[h]:mm:ss

…which will show numbers of hours for durations longer than 24 hours. If you type “48:00:11” into an Excel cell, it will create that custom format for you (at least, it did in Excel 2007 on my machine just now). Removing formatting shows the value to be the expected double (which all non-strings are): 2.000127, which is the number of days (with time as fraction) for the duration.

Putting that string value into a worksheet from C# may have a different outcome: I suspect so from the 48.007638… value you obtained. Since you have C# at your disposal I would be inclined to calculate the timespan as a number of days prior to pushing the value to Excel, then formatting as above.