Search code examples
c#type-conversiontimespandate-manipulation

Convert Ticks to TimeSpan


I want to convert Ticks to TimeSpan.

I need a ConvertToTimeSpan function like below.

var ticks = 10000;
TimeSpan ts = ConvertToTimeSpan(ticks);  // not working
Console.WriteLine(ts);  // expected output --> {00:00:00.0010000}

Solution

  • There is a TimeSpan(Int64) constructor, which accepts a number of ticks:

    https://msdn.microsoft.com/en-us/library/zz841zbz(v=vs.110).aspx

    Initializes a new instance of the TimeSpan structure to the specified number of ticks.

    In .NET, Ticks are always represented as Int64, so you should not use var ticks = 1 because that's an implicit Int32, so you will end-up using the wrong method overload. Instead specify an explicit type declaration or a long literal value (var ticks = 1L).