C# DateTime Ticks

Description

DateTime Ticks gets the number of ticks that represent the date and time of this instance.

Syntax

DateTime.Ticks has the following syntax.


public long Ticks { get; }

Example

The following example uses the Ticks property to display the number of ticks that have elapsed since the beginning of the twenty-first century and to instantiate a TimeSpan object.


using System;/*  w  ww  .j  av  a  2 s .com*/
public class MainClass{
  public static void Main(String[] argv){  
    DateTime centuryBegin = new DateTime(2001, 1, 1);
    DateTime currentDate = DateTime.Now;
    
    long elapsedTicks = currentDate.Ticks - centuryBegin.Ticks;
    TimeSpan elapsedSpan = new TimeSpan(elapsedTicks);
    
    System.Console.WriteLine("Elapsed from the beginning of the century to {0:f}:", 
                       currentDate);
    System.Console.WriteLine("   {0:N0} nanoseconds", elapsedTicks * 100);
    System.Console.WriteLine("   {0:N0} ticks", elapsedTicks);
    System.Console.WriteLine("   {0:N2} seconds", elapsedSpan.TotalSeconds);
    System.Console.WriteLine("   {0:N2} minutes", elapsedSpan.TotalMinutes);
    System.Console.WriteLine("   {0:N0} days, {1} hours, {2} minutes, {3} seconds", 
                      elapsedSpan.Days, elapsedSpan.Hours, 
                      elapsedSpan.Minutes, elapsedSpan.Seconds);  

  }
}
    

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version