C#:如何将 TimeSpan 值转换为双精度值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16252911/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:33:26  来源:igfitidea点击:

C#: How do I convert a TimeSpan value to a double?

c#.netdatetimedoubletimespan

提问by user2037696

How do I convert a TimeSpanvalue to a doublein C#?

如何在 C# 中将TimeSpan值转换为 a double

I mean I have this -08:15:00and I want a double -08.15.

我的意思是我有这个-08:15:00,我想要一个 double -08.15

回答by albattran

You can use string.format, then parse it like this:

您可以使用 string.format,然后像这样解析它:

   double.Parse(string.Format("-HH.mm"))

回答by tukaef

Do not repeat this at home!

不要在家里重复这个!

double value = (timeSpan.Hours + timeSpan.Minutes / 100.0 + timeSpan.Seconds / 10000.0) * (timeSpan > TimeSpan.Zero ? 1 : -1);

回答by Umar Farooq Khawaja

You could use TimeSpan.TotalMinutes(gets the value of the current TimeSpanstructure expressed in whole and fractional minutes) or other similar properties.

您可以使用TimeSpan.TotalMinutes(获取TimeSpan以整数和小数分钟表示的当前结构的值) 或其他类似属性

回答by Digital_Utopia

Despite how ambiguous this question is, for future reference, Umar was probably the closest to answering the question, as it was displayed in the title.

尽管这个问题有多么模棱两可,但为了将来参考,奥马尔可能是最接近回答这个问题的人,因为它显示在标题中。

To get a doublefrom a TimeSpanobject, you need to pick the most significant measurement, and get the total. As the Total<x>property, will return the appropriate full value, and the fractions of that value as a decimal.

为了得到一个doubleTimeSpan对象,你需要选择最显著的测量,并获得总。作为Total<x>属性,将返回适当的完整值,并将该值的分数作为小数。

So, if you want 8:15:00, to a double- and the "8"represents Hours, then you'll want TimeSpan.TotalHourswhich will result in a value of 8.25.

因此,如果您想要8:15:00, 到 a double- 和"8"代表Hours,那么您将希望TimeSpan.TotalHours得到 8.25 的值。

If the "8"represents Minutes, then again, you'll use the appropriate property TimeSpan.TotalMinutesfor the same result, and so on.

如果"8"代表Minutes,那么您将再次使用适当的属性TimeSpan.TotalMinutes来获得相同的结果,依此类推。