Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse time string to decimal?

Tags:

c#

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

like image 750
jmasterx Avatar asked Mar 28 '13 19:03

jmasterx


People also ask

How do you convert time to numbers?

To convert time to a number of hours, multiply the time by 24, which is the number of hours in a day. To convert time to minutes, multiply the time by 1440, which is the number of minutes in a day (24*60). To convert time to seconds, multiply the time time by 86400, which is the number of seconds in a day (24*60*60 ).


2 Answers

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.

like image 103
Lance U. Matthews Avatar answered Oct 05 '22 08:10

Lance U. Matthews


private decimal TimeToDecimal(string Time)
{
    DateTime dt = DateTime.Parse(Time);
    decimal result = dt.Hour+ (dt.Minute / 60.0m);
    return result;
}
like image 40
K0D4 Avatar answered Oct 05 '22 08:10

K0D4