2

I have some code which takes for example, 27:30 (27 hours 30 minutes) and converts it to a decimal like 27.5. I have another function that does the opposite.

 public class Time
    {
        public static string Hours(decimal d)
        {
            return TimeSpan.FromHours((double)(d + 0.005M)).ToString("h\\:mm");
        }

        public static decimal Hours(string s)
        {
            decimal r;
            if (decimal.TryParse(s, out r))
                return r;

            return (decimal)TimeSpan.Parse(s).TotalHours + 0.005M;
        }
    }

The problem is that the conversion from decimal to string seems to wrap to 24 hours. If I give it 30.0 it gives me 6:00 which is wrong. It should be 30:00

What could I do to avoid the wrap?

Thanks

jmasterx
  • 52,639
  • 96
  • 311
  • 557
  • 2
    It's not wrapping at 24 hours, you have to look at the "Days" property as well. For 30 hours, Days=1 and Hours=6. That's why you are seeing "6:00". – David Apr 01 '13 at 20:21
  • @ConradFrix, the "h" in the TimeSpan's ToString does not show the "TotalHours". It pulls from just the "Hours" property. – David Apr 01 '13 at 21:39
  • @David my mistake I was looking `Hours(string s)` instead of `Hours(decimal)` – Conrad Frix Apr 01 '13 at 21:43

3 Answers3

3

There is no format specifier for TotalHours, so you have to write whole logic by yourself:

public static string Hours(decimal d)
{
    var ts = TimeSpan.FromHours((double)(d + 0.005M));
    return string.Format("{0:0}:{1:00}", (int)ts.TotalHours, ts.Minutes);
}

(int)ts.TotalHours casting truncates minuts from number of hours.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
0

Use DateTime.ToString to get the minutes only, and calculate the hours yourself.

return string.Format("{0:0}:{1}", Math.Truncate(d+0.005m), TimeSpan.FromHours(d+0.005m).ToString("mm"));
Matthew
  • 24,703
  • 9
  • 76
  • 110
0

The h format only reports hours not counted as parts of days. See here.

You can either output the number of days by adding a d or perform the conversion in your own code if you want a non-standard behavior.

HABO
  • 15,314
  • 5
  • 39
  • 57