Converting a float into a timespan
Asked Answered
P

2

25

Is there a simple way to take a float value representing fractional hours and convert them into a TimeSpan 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?

Prodigy answered 2/5, 2012 at 20:28 Comment(0)
G
57

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;
Gnostic answered 2/5, 2012 at 20:29 Comment(0)
C
12

So, you're looking for... TimeSpan.FromHours(double)?

The documentation is your friend.

Christmas answered 2/5, 2012 at 20:29 Comment(5)
That 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 what TimeSpan.FromHours would do?Blindstory
I 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.Blindstory
Indeed, it should be TimeSpan.FromThreePointSixMillionMilliseconds to make sense.Coprology
ToHours() - would have been some form of improvement, to say "FromHours" infers that you are doing something from an hours value.Livonia
@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 a TimeSpanChristmas

© 2022 - 2024 — McMap. All rights reserved.