5

In .Net, is there a way to convert, say, '2:45' to the decimal 2.75?

ex:

decimal d = TimeToDecimal("2:45");
Console.WriteLine(d);

//output is 2.75

It should throw an exception if invalid data, ex, minutes < 0 < 60 or not in the h:m format.

Thanks

jmasterx
  • 52,639
  • 96
  • 311
  • 557
  • Duplicate of http://stackoverflow.com/q/5366285/82682 – joce Mar 28 '13 at 19:37
  • Totally. The "hard" part is `DateTime.Parse()` that will throw the required exception. The rest is about dividing by 60. This is a dupe. – joce Mar 28 '13 at 19:45

2 Answers2

13

The following will output 2.75:

TimeSpan time = TimeSpan.Parse("2:45");
decimal d = (decimal) time.TotalHours;

Console.WriteLine(d);

Note that the TimeSpan.TotalHours property is of type double, not decimal.

From the documentation for the TimeSpan.Parse method, it will throw an OverflowException if "At least one of the days, hours, minutes, or seconds components is outside its valid range", so that should take care of input validation for you. See also the TimeSpan.TryParse method.

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
4
private decimal TimeToDecimal(string Time)
{
    DateTime dt = DateTime.Parse(Time);
    decimal result = dt.Hour+ (dt.Minute / 60.0m);
    return result;
}
K0D4
  • 2,373
  • 1
  • 27
  • 26
  • I think you want it to read: `decimal result = dt.Hour + (dt.Minute / 60.0m);` – rsbarro Mar 28 '13 at 19:41
  • I suppose the best solution would be `decimal result = dt.Hour + (dt.Minute / 60.0m) + (dt.Second / 3600.0m);` – K0D4 Mar 28 '13 at 19:44