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

5

9

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

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

Philanthropy answered 27/4, 2013 at 13:53 Comment(3)
Why would you want to do that? 8 minutes and 15 seconds is not equal to 8.15 minutes.Naturism
@KirkWoll: It's not unheard of to represent an angle such as 22°39'46" like 22.3946, so maybe that's what OP wants.Wilscam
Everything considered, your question is ambiguous at best. is 8:15:00 h/m/s, or is it m/s/ms? And did you really mean 8:15:00 -> 8.15, or should it be 8:15:00 -> 8.25?Succession
S
18

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. As the Total<x> property, will return the appropriate full value, and the fractions of that value as a decimal.

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.

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

Succession answered 29/9, 2014 at 9:5 Comment(1)
Thank you for the quick reference, I wonder if OP was downvoted because of the wrong conversion from -08:15:00 to -08.15 instead of -08.25, the question itself is legit in itself. If you are making a system that is to be used by book keepers to manage salary based on how much you've worked you'll need something like this.Gooseflesh
N
11

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

Nerin answered 27/4, 2013 at 14:0 Comment(0)
E
3

Do not repeat this at home!

double value = (timeSpan.Hours + timeSpan.Minutes / 100.0 + timeSpan.Seconds / 10000.0) * (timeSpan > TimeSpan.Zero ? 1 : -1);
Eurythmics answered 27/4, 2013 at 13:59 Comment(4)
This won't be accurate because it will ignore Days, Hours and Milliseconds.Nerin
@UmarFarooqKhawaja Not Hours, actuallyLusterware
Indeed, @VMAtm!Nerin
how about: (timeSpan.Hours + timeSpan.Minutes / 60.0 + timeSpan.Seconds / 3600.0) * (timeSpan > TimeSpan.Zero ? 1 : -1);Dialyze
S
0

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.

With a functional mindset:

public static class Extension
{
    public static double ToDouble(this TimeSpan o) => o.TotalDays;
}
Sexennial answered 25/10, 2020 at 0:16 Comment(0)
L
-1

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

   double.Parse(string.Format("-HH.mm"))
Lura answered 27/4, 2013 at 13:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.