Click here to Skip to main content
15,667,885 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
How can I convert a TimeSpan object to an equivalent integer value? Thank you.
Updated 18-Jan-11 3:21am
Richard MacCutchan 18-Jan-11 9:13am    
Depending on what units you use, a timespan is an integer.

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:

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:

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.
Share this answer
fjdiewornncalwe 18-Jan-11 15:06pm    
"Useful? Maybe, maybe not. Fun to code? Yep."... +5...
I'll have to assume that the tag is wrong, and that you are thinking of the .net System.TimeSpan structure.

If you are, then System.TimeSpan.Ticks[^] is your answer.

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

If you are thinking about something else I'll need more info ...

Espen Harlinn
Share this answer
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?
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    
Good answer, voted 5, proposed as answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900