w3resource logo
C# Sharp Programming Exercises

C# Sharp Exercises: Add millisecond to a given date

C# Sharp DateTime: Exercise-12 with Solution

Write C# Sharp Program to add one millisecond and 2.5 milliseconds to a given date value and display each new value and the difference between it and the original value.

Note: The difference is displayed both as a time span and as a number of ticks and one millisecond equals 10,000 ticks.

Sample Solution:-

C# Sharp Code:

using System;

public class Example12
   public static void Main()
    string dateFormat = "MM/dd/yyyy hh:mm:ss.fffffff"; 
    DateTime date1 = new DateTime(2016, 8, 16, 16, 0, 0);
    Console.WriteLine("Original date: {0} ({1:N0} ticks)\n",
                  date1.ToString(dateFormat), date1.Ticks);

    DateTime date2 = date1.AddMilliseconds(1);
    Console.WriteLine("Second date:   {0} ({1:N0} ticks)",
                  date2.ToString(dateFormat), date2.Ticks);
    Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)\n",
                  date2 - date1, date2.Ticks - date1.Ticks);                        

    DateTime date3 = date1.AddMilliseconds(2.5);
    Console.WriteLine("Third date:    {0} ({1:N0} ticks)",
                  date3.ToString(dateFormat), date3.Ticks);
    Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)",
                  date3 - date1, date3.Ticks - date1.Ticks); 


Sample Output:

Original date: 08/16/2016 04:00:00.0000000 (636,069,600,000,000,000 ticks)             
Second date:   08/16/2016 04:00:00.0010000 (636,069,600,000,010,000 ticks)             
Difference between dates: 00:00:00.0010000 (10,000 ticks)                              
Third date:    08/16/2016 04:00:00.0030000 (636,069,600,000,030,000 ticks)             
Difference between dates: 00:00:00.0030000 (30,000 ticks)

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus