Convert DateTime to Ticks and Ticks to DateTime in C#

This article contains C# code snippets to convert DateTime to Ticks and Ticks to DateTime

Summary

What is Ticks

     Ticks represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.

Convert DateTime to Ticks in C#

class DateTimeToTicksConverter
     {
        static void Main(string[] args)
           {
             //Function call to convert DateTime to Ticks
                long ticks = ConvertDateTimeToTicks(DateTime.Now);
                Console.WriteLine(ticks.ToString());           
                Console.Read();
           }

        static long ConvertDateTimeToTicks(DateTime datetime)
          {
               long  ticks=datetime.Ticks;
               return ticks;
          }         
    }

Convert Ticks to DateTime in C#

class TicksToDateTimeConverter
     {
        static void Main(string[] args)
           {             

           //Function call to convert Ticks to DateTime
               DateTime datetime = ConvertTicksToDateTime(ticks);
               Console.WriteLine(datetime.ToString());
               Console.Read();
          }
        
        static DateTime ConvertTicksToDateTime(long ticks)
          {
              DateTime datetime= new DateTime(ticks);
              return datetime;
          }
    }

Related Articles:

– Get current time on a remote system using C# 
– Convert Object To Byte Array and Byte Array to Object in C#
– Add or Remove programs using C# in Control Panel 
– Show balloon tooltip c#
– How to read data from csv file in c# 
– Bulk Insert into SQL Server using SqlBulkCopy in C#
– Import CSV File Into SQL Server Using SQL Bulk Copy

Advertisement

Leave a Comment