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.

Share:
26,875

Related videos on Youtube

Icemanind
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, 2020

Comments

  • Icemanind
    Icemanind over 4 years

    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?

  • Jon Skeet
    Jon Skeet about 12 years
    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?
  • Jon Skeet
    Jon Skeet about 12 years
    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.
  • Michael Stum
    Michael Stum about 12 years
    Indeed, it should be TimeSpan.FromThreePointSixMillionMilliseconds to make sense.
  • Vidar
    Vidar over 9 years
    ToHours() - would have been some form of improvement, to say "FromHours" infers that you are doing something from an hours value.
  • Ed S.
    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 a TimeSpan