c# - How to get two DateTime objects difference in milliseconds

DateTime difference in Milliseconds
the following asp.net c# example source code demonstrate us how can we get difference in milliseconds between two datetime objects. in this source code, we created a datetime type variable by DateTime.Now property that holds a value that represent the current system date and time. now we initialize a new datatime variable with a value that is two minutes greater than previous datetime variable.

after initializing two datetime variables, we create a timespan object by subtract two datetime object. at last we convert the timespan object into milliseconds. the converted milliseconds is the difference between two datetime objects.

DateTime.Now property gets a datetime object that represent current date and time on web server. DateTime.Subtract() method subtract two datetime objects and return a timespan object. TimeSpan represents a time interval.

<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>      
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
        //initialize a datetime variable with current datetime
        DateTime now = DateTime.Now;

        Label1.Text = "now : " + now.ToString();

        //add 2 minutes to current time
        DateTime dateAfter2Minutes = now.AddMinutes(2);

        TimeSpan ts = dateAfter2Minutes - now;
        //total milliseconds difference between two datetime object
        int milliseconds = (int)ts.TotalMilliseconds;
        Label1.Text += "<br ><br />after two minutes: ";
        Label1.Text += dateAfter2Minutes.ToString();

        Label1.Text += "<br ><br />smillieconds difference between to datetime object : ";
        Label1.Text += milliseconds;
<html xmlns="http://www.w3.org/1999/xhtml">      
<head id="Head1" runat="server">      
    <title>c# example - datetime difference in milliseconds</title>      
    <form id="form1" runat="server">      
        <h2 style="color:MidnightBlue; font-style:italic;">      
            c# example - datetime difference in milliseconds
        <hr width="550" align="left" color="Gainsboro" />      
            Font-Names="Comic Sans MS"
        <br /><br />    
            Text="get milliseconds difference between two datetime"      
The above image describe this example code better. this output screenshot display that at first line we created a DateTime variable. second line we created another datetime object by adding two minutes with first datetime object. final line shows the difference of two datetime objects in milliseconds. one second equal to one thousand milliseconds.

More c# examples