float表示小时到小时:分钟:秒使用c#

时间:2021-10-09 02:47:39

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

我需要将表示小时的浮点数转换为小时:分钟:秒。

How is that possible by using C#.

如何使用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.

目前我正在将这个5.4898391027272906浮动小时转换为小时分钟和秒,我得到的结果只有几小时和几分钟而不是秒。

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

结果:小时= 5,分钟= 29,秒= 176

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

但我希望在60秒之间获得一秒钟。

2 个解决方案

#1


How about using TimeSpan.FromHours method?

如何使用TimeSpan.FromHours方法?

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.

不要对时间间隔使用某些整数计算。这正是TimeSpan的用途。

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.

顺便说一句,你的代码甚至不会编译。没有任何后缀,你的5.4898391027272906将是double而不是float,并且没有从double到float的隐式对话。您需要使用f或F后缀。而这个TimeSpan.FromHours方法将double作为参数,而不是float。

#2


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.

你的原始方法不起作用,因为一小时有3600秒,而不是360,并且因为使用模数这样无论如何都不起作用!您可以从分钟获得秒数,例如29.39分钟* 60%60 = 23.4秒。

#1


How about using TimeSpan.FromHours method?

如何使用TimeSpan.FromHours方法?

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.

不要对时间间隔使用某些整数计算。这正是TimeSpan的用途。

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.

顺便说一句,你的代码甚至不会编译。没有任何后缀,你的5.4898391027272906将是double而不是float,并且没有从double到float的隐式对话。您需要使用f或F后缀。而这个TimeSpan.FromHours方法将double作为参数,而不是float。

#2


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.

你的原始方法不起作用,因为一小时有3600秒,而不是360,并且因为使用模数这样无论如何都不起作用!您可以从分钟获得秒数,例如29.39分钟* 60%60 = 23.4秒。