In .Net, is there a way to convert, say, '2:45'to decimal 2.75?
'2:45'
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
Next will output 2.75:
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
TimeSpan.TotalHours
double
decimal
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.
TimeSpan.Parse
OverflowException
TimeSpan.TryParse
private decimal TimeToDecimal(string Time) { DateTime dt = DateTime.Parse(Time); decimal result = dt.Hour+ (dt.Minute / 60.0m); return result; }