Converting a float into a timespan
26,875
Solution 1
You want the FromHours
method.
This takes a double (rather than a float) and returns a TimeSpan
:
double hours = 1.5;
TimeSpan interval = TimeSpan.FromHours(hours);
To get the total hours from a TimeSpan
use the TotalHours
property:
TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750);
double hours = interval.TotalHours;
Solution 2
So, you're looking for... TimeSpan.FromHours(double)?
The documentation is your friend.
Related videos on Youtube
Author by
Icemanind
I am a .NET developer. I am proficient in C# and I use ASP.Net Core, Winforms and WPF. I also dabble in React and Xamarin.
Updated on January 24, 2020Comments
-
Icemanind over 4 years
Is there a simple way to take a
float
value representing fractional hours and convert them into aTimeSpan
object and visa versa? For example:float oneAndAHalfHours = 1.5f; float twoHours = 2f; float threeHoursAndFifteenMinutes = 3.25f; float oneDayAndTwoHoursAndFortyFiveMinutes = 26.75f; TimeSpan myTimeSpan = ConvertToTimeSpan(oneAndAHalfHours); // Should return a TimeSpan Object
Any ideas?
-
Jon Skeet about 12 yearsThat naming scheme's just crazy. So undiscoverable. Who'd have thought that if I wanted to create a
TimeSpan
from a number of hours, that that's whatTimeSpan.FromHours
would do? -
Jon Skeet about 12 yearsI would pay good money to see a date/time API designed by Eric. I actually mean that entirely literally... I think the value I'd gain in comparing his decisions to the ones I've taken in Noda Time would be worth quite a bit to me.
-
Michael Stum about 12 yearsIndeed, it should be
TimeSpan.FromThreePointSixMillionMilliseconds
to make sense. -
Vidar over 9 yearsToHours() - would have been some form of improvement, to say "FromHours" infers that you are doing something from an hours value.
-
Ed S. over 9 years@Vidar: Except it's a static method, so
ToHours(hours)
makes no sense.ToXXX
only really makes sense as an instance method. "'FromHours' infers that you are doing something from an hours value. - It implies that, yes, because that's exactly what it is doing. You provide the hours, it returns aTimeSpan