15,997,667 members
3.00/5 (1 vote)
See more:
How can I convert a `TimeSpan `object to an equivalent integer value? Thank you.
Posted
Updated 18-Jan-11 3:21am
v3
Richard MacCutchan 18-Jan-11 9:13am
Depending on what units you use, a timespan is an integer.

## Solution 2

I know this has halready had a response marked as the answer, but I was thinking it might be fun to look at it from another viewpoint...

First `TimeSpan` is represented internally as a `long` (just get the `TimeSpan.Ticks` property, and Bob's your uncle), so it's already an integer type.

Second, you could convert it to a decimal, just for the coding exercise:

C#
```public static class ExtensionMethods
{
//-------------------------------------------------------------
public static decimal ToDecimal(this TimeSpan span)
{
decimal spanSecs = (span.Hours * 3600) + (span.Minutes * 60) + span.Seconds;
decimal spanPart = spanSecs / 86400M;
decimal result = span.Days + spanPart;
return result;
}
//-------------------------------------------------------------
public static TimeSpan ToTimeSpan(this decimal value)
{
int days = Convert.ToInt32(Math.Ceiling(value));
value -= days;
int time = Convert.ToInt32(value * 86400M);
TimeSpan result = new TimeSpan(1, 0, 0, time, 0);
return result;
}
}```

Usage would be thus:

C#
```TimeSpan span          = new TimeSpan(0,12,0,0,0);
decimal  spanAsDecimal = span.ToDecimal();
TimeSpan span2         = spanAsDecimal.ToTimeSpan();```

Useful? Maybe, maybe not. Fun to code? Yep.

Caveat: This doesn't take milliseconds into account, but it would be easy to add.

v4
fjdiewornncalwe 18-Jan-11 15:06pm
"Useful? Maybe, maybe not. Fun to code? Yep."... +5...

## Solution 1

I'll have to assume that the tag is wrong, and that you are thinking of the .net System.TimeSpan structure.

```int intValueLow32Bits = Convert.ToInt32( 0x00000000FFFFFFFF & ticksAsLong );
int intValueHigh32Bits = Convert.ToInt32( ticksAsLong >> 32 );
```

Regards
Espen Harlinn

v2
E.F. Nijboer 18-Jan-11 9:12am
Would be answer also. Be aware 1nagaswarupa that the ticks gives an int64.
Espen Harlinn 18-Jan-11 9:13am
Good point :)
Sergey Alexandrovich Kryukov 18-Jan-11 9:14am
Hi Espen,
How did you know the question was about .NET?
--SA
JF2015 18-Jan-11 9:15am
Alright, I also assume that the tag was wrong - otherwise I had no idea what he's talking about. Great answer. 5+
Nish Nishant 18-Jan-11 9:20am