Home
C#
Convert TimeSpan to Long
Updated Sep 3, 2022
Dot Net Perls
Convert TimeSpan, Long. In the C# programming language, TimeSpan and long are the same number of bytes. It is possible to store a TimeSpan as a long.
Conversion info. Converting a TimeSpan to a long can be done with the Ticks property on TimeSpan. It is easier to persist a long in storage.
long, ulong
Example. In this program, we get two DateTimes. Then we get the difference as a TimeSpan instance. Next, we convert that TimeSpan into a long Ticks.
Finally We convert that long Ticks back into a TimeSpan, showing that you can round-trip longs and TimeSpans.
using System; class Program { static void Main() { // Difference between today and yesterday. DateTime yesterday = DateTime.Now.Subtract(TimeSpan.FromDays(1)); DateTime now = DateTime.Now; TimeSpan diff = now.Subtract(yesterday); // TimeSpan can be represented as a long [ticks]. long ticks = diff.Ticks; // You can convert a long [ticks] back into TimeSpan. TimeSpan ts = TimeSpan.FromTicks(ticks); // Display. Console.WriteLine(ts); // Note: long and TimeSpan are the same number of bytes [8]. unsafe { Console.WriteLine(sizeof(long)); Console.WriteLine(sizeof(TimeSpan)); } } }
1.00:00:00.0010000 8 8
Byte count. In the unsafe context, the program shows that a long is 8 bytes and a TimeSpan is also 8 bytes. Therefore, it is logical for one to fit in the other.
sizeof
TimeSpan
Summary. It is possible to convert from a TimeSpan and a long using the Ticks property and the FromTicks method. Sometimes a long representation is more useful for external systems.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 3, 2022 (rewrite).
Home
Changes
© 2007-2025 Sam Allen