[英]C#: How do I convert a TimeSpan value to a double?
How do I convert a TimeSpan
value to a double
in C#?如何在 C# 中将TimeSpan
值转换为double
TimeSpan
值?
I mean I have this -08:15:00
and I want a double -08.15
.我的意思是我有这个-08:15:00
并且我想要一个双-08.15
。
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 double
from a TimeSpan
object, you need to pick the most significant measurement, and get the total.要从TimeSpan
对象获得double
TimeSpan
值,您需要选择最重要的测量值,并获得总数。 As the Total<x>
property, will return the appropriate full value, and the fractions of that value as a decimal.作为Total<x>
属性,将返回适当的完整值,以及该值的小数部分作为小数。
So, if you want 8:15:00
, to a double
- and the "8"
represents Hours
, then you'll want TimeSpan.TotalHours
which will result in a value of 8.25.所以,如果你想8:15:00
,以一个double
-和"8"
代表Hours
,那么你会希望TimeSpan.TotalHours
这将导致8.25的数值。
If the "8"
represents Minutes
, then again, you'll use the appropriate property TimeSpan.TotalMinutes
for the same result, and so on.如果"8"
代表Minutes
,那么您将再次使用适当的属性TimeSpan.TotalMinutes
来获得相同的结果,依此类推。
您可以使用TimeSpan.TotalMinutes
(获取以整数和小数分钟表示的当前TimeSpan
结构的值)或其他类似属性。
不要在家里重复这个!
double value = (timeSpan.Hours + timeSpan.Minutes / 100.0 + timeSpan.Seconds / 10000.0) * (timeSpan > TimeSpan.Zero ? 1 : -1);
In the case of operations with DateTime
in its double
format obtained with .ToOADate()
, TimeSpan
must be converted to double
directly with .TotalDays
since the unit (1.0) for DateTime
is a day.对于使用.ToOADate()
获得的double
.ToOADate()
格式的DateTime
的操作,必须使用.ToOADate()
TimeSpan
直接转换为double
.TotalDays
因为DateTime
的单位 (1.0) 是一天。
With a functional mindset:以功能性思维:
public static class Extension
{
public static double ToDouble(this TimeSpan o) => o.TotalDays;
}
您可以使用 string.format,然后像这样解析它:
double.Parse(string.Format("-HH.mm"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.