BeanSoftware Logo
 

 
ASP.NET Database Search Control
 
 

 
 Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

How To 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.");
 
}

[ VB.NET ]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' Declare and get DateTime values
    Dim StartDate As DateTime = System.DateTime.Now
    Dim EndDate As DateTime = System.DateTime.UtcNow
 
    ' Find time difference between two dates
    Dim TimeDifference As TimeSpan = 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 Then
        Response.Write(" and " & TimeDifference.Minutes.ToString() & " minutes.")
    End If
End Sub



Related articles:

1. Control Template in DataGrid, Repeater and DataList Controls
2. Publishing And Reading RSS Feeds In ASP.NET

FAQ toolbar: Submit FAQ  |  Tell A Friend  |  Add to favorites  |  Feedback



Copyright © 2002-2008 Bean Software. All rights reserved.