Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a float into a timespan

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?

like image 258
Icemanind Avatar asked Sep 10 '25 09:09

Icemanind


1 Answers

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;
like image 97
ChrisF Avatar answered Sep 12 '25 23:09

ChrisF