Mirza Danish Baig
Mirza Danish Baig

Reputation: 680

float representing hours to hours:minutes:seconds using c#

I need to convert a float representing hours to Hours:Minutes:Seconds.

How is that possible by using C#.

Currently i am converting this 5.4898391027272906 float hour to Hours minutes and seconds, i got a desire results for only till hours and minutes but not for seconds.

Below is my code:

double time = 5.4898391027272906;
double hours = Math.Floor(time);
double minutes = Math.Floor(time * 60 % 60);
double seconds = Math.Floor(time * 360 % 360);

Result: hours = 5, minutes = 29 and seconds = 176

but i want to get a seconds in between 60 seconds.

Upvotes: 0

Views: 4086

Answers (2)

IglooGreg
IglooGreg

Reputation: 147

Your original method wouldn't work because there are 3600 seconds in an hour, not 360, and because using modulo like that doesn't work anyway! You could get the seconds from the minutes, e.g. 29.39 minutes * 60 % 60 = 23.4 seconds.

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98750

How about using TimeSpan.FromHours method?

var ts = TimeSpan.FromHours(5.4898391027272906);
Console.WriteLine(ts.Seconds); // 23

Don't use some integer calculations for time intervals. This is exactly what TimeSpan is for.

By the way, you code won't even compile. Without any suffix, your 5.4898391027272906 will be double not float and there is no implicit conversation from double to float. You need to use f or F suffix. And this TimeSpan.FromHours method takes double as a parameter, not float.

Upvotes: 6

Related Questions