Align temporary string to decimal?

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

Example:

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

//output is 2.75

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

thank

+5
source share
2 answers

Next will output 2.75:

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

Console.WriteLine(d);

Note that the property is of type , not . TimeSpan.TotalHoursdoubledecimal

From the documentation for the method, a TimeSpan.Parsevalue will be selected OverflowExceptionif: "At least one of the components of days, hours, minutes or seconds is outside its acceptable range", so you should take care to confirm the entry. See also method TimeSpan.TryParse.

+13
source
private decimal TimeToDecimal(string Time)
{
    DateTime dt = DateTime.Parse(Time);
    decimal result = dt.Hour+ (dt.Minute / 60.0m);
    return result;
}
+4

All Articles