C# difference in milliseconds between two DateTime

CsharpProgrammingServer Side Programming

Let’s say the following are two DateTime objects for our dates.

DateTime date1 = new DateTime(2018, 8, 11, 08, 15, 20);
DateTime date2 = new DateTime(2018, 8, 11, 11, 14, 25);

Find the difference between both these dates using TimeSpan.

TimeSpan ts = date2 - date1;

Now to get the Milliseconds, use the following property −

ts.TotalMilliseconds

Let us see the complete code.

Example

 Live Demo

using System;
using System.Linq;
public class Demo {
   public static void Main() {
      DateTime date1 = new DateTime(2018, 8, 11, 08, 15, 20);
      DateTime date2 = new DateTime(2018, 8, 11, 11, 14, 25);
      TimeSpan ts = date2 - date1;
      Console.WriteLine("No. of Seconds (Difference) = {0}", ts.TotalMilliseconds);
   }
}

Output

No. of Seconds (Difference) = 10745000
raja
Published on 12-Sep-2018 12:01:45
Advertisements