DateTime.AddTicks() Method in C#


The DateTime.AddTicks() method in C# is used to add a specified number of ticks to the value of this instance. It returns a new DateTime.

Syntax

Following is the syntax −

public DateTime AddTicks (long ticks);

Here, ticks value is for 100-nanosecond.

Example

Let us now see an example to implement the DateTime.AddTicks() method −

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 07, 25, 6, 20, 40);
      DateTime d2 = d1.AddTicks(5000);
      System.Console.WriteLine("DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      System.Console.WriteLine("Initial Ticks = {0} ", d1.Ticks);
      System.Console.WriteLine("New Ticks = {0} ", d2.Ticks);
   }
}

Output

This will produce the following output −

DateTime = 25 July 2019, 06:20:40
Initial Ticks = 636996324400000000
New Ticks = 636996324400005000

Example

Let us now see another example to implement the DateTime.AddTicks() method −

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 07, 25, 6, 20, 40);
      DateTime d2 = d1.AddTicks(-5000);
      System.Console.WriteLine("DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      System.Console.WriteLine("Initial Ticks = {0} ", d1.Ticks);
      System.Console.WriteLine("New Ticks (subtracting) = {0} ", d2.Ticks);
   }
}

Output

This will produce the following output −

DateTime = 25 July 2019, 06:20:40
Initial Ticks = 636996324400000000
New Ticks = 636996324399995000

Updated on: 11-Nov-2019

662 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements