30 December 2011

Calculate Time Difference Between DateTime Objects


Calculate Time Difference Between DateTime Objects

To get time difference you need to use TimeSpan object, with code like this:
TimeSpan ts = DateTime1 - DateTime2;
For example, if you want to calculate time difference between server time and UTC time:
[ C# ]
protected void Page_Load(object sender, EventArgs e)
{
    // Declare and get DateTime values
    DateTime StartDate = System.DateTime.Now;
    DateTime EndDate = System.DateTime.UtcNow;
 
    // Find time difference between two dates
    TimeSpan TimeDifference = StartDate - EndDate;
 
    // Write difference in hours and minutes
    Response.Write("Time difference between server time and Coordinated Universal Time (UTC) is " + 
        TimeDifference.Hours.ToString() + " hours ");
    if (TimeDifference.Minutes != 0)
        Response.Write(" and " + TimeDifference.Minutes.ToString() + " minutes.");
 
}

2 comments:

  1. Dada, Suppose that I have two datetime object both are getting used to hold dates. Now if I subtract the two object in this way will I get the resultant year/month/days ?

    ReplyDelete
  2. No,its not possible. you have to add seconds or minutes with datetime to achieve this.

    ReplyDelete

Comments Welcome

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...