C# 将浮点数转换为时间跨度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10421178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a float into a timespan
提问by Icemanind
Is there a simple way to take a floatvalue representing fractional hours and convert them into a TimeSpanobject and visa versa? For example:
有没有一种简单的方法来获取float表示小数小时的值并将它们转换为TimeSpan对象,反之亦然?例如:
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?
有任何想法吗?
采纳答案by ChrisF
You want the FromHoursmethod.
你想要FromHours方法。
This takes a double (rather than a float) and returns a TimeSpan:
这需要一个双精度(而不是一个浮点数)并返回一个TimeSpan:
double hours = 1.5;
TimeSpan interval = TimeSpan.FromHours(hours);
To get the total hours from a TimeSpanuse the TotalHoursproperty:
要从TimeSpan使用该TotalHours属性中获取总小时数:
TimeSpan interval = new TimeSpan(1, 15, 42, 45, 750);
double hours = interval.TotalHours;
回答by Ed S.
So, you're looking for... TimeSpan.FromHours(double)?
那么,您正在寻找... TimeSpan.FromHours(double)?
The documentation is your friend.
文档是您的朋友。

