TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Convert TimeSpan to Long

This C# example program converts a TimeSpan to a long. It converts the long to a TimeSpan.

Convert TimeSpan, long. TimeSpan and long are the same number of bytes.

It is possible to store a TimeSpan as a long. This can be done with the Ticks property on TimeSpan. It is easier to persist a long in storage. We examine TimeSpan and its representation.

Long

Example. In this program, we get two DateTimes. The first one is for "now." The second is for a day ago. 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.

C# program that converts TimeSpan to long

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));
	}
    }
}

Output

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. It may be easier to write a long to a file or a database.

SizeofTimeSpan Examples

Summary. We saw how it is possible to convert from a TimeSpan and a long using the Ticks property and also the FromTicks method. By providing a long representation, the TimeSpan becomes more useful for external systems.

Because: External systems often support simple numeric types better than struct types.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf