How to calculate Time Difference Between Two Date Time in ASP.NET C# VB.Net

In some cases ASP.NET C# VB.Net developers need to find out Time Difference or timediff method or timediff function to get the time between two Time. Here in this article i will show you how you can achieve this:

C# Code to Get Time Difference:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            DateTime dtFrom;
            DateTime dtTo;
            string sFrom = "10:35:00";
            string sTo = "12:50:00";
            if (DateTime.TryParse(sFrom, out dtFrom) && DateTime.TryParse(sTo, out dtTo))
                TimeSpan tSpan = dtTo - dtFrom;
                int nDay = tSpan.Days;
                int nHour = tSpan.Hours;
                int nMin = tSpan.Minutes;
                int nSec = tSpan.Seconds;
                string sTimeDiff = nDay.ToString("00") + ":" + nHour.ToString("00") + ":" + nMin.ToString("00") + ":" + nSec.ToString("00");
                Response.Write(sTimeDiff); //output format 00:02:15:00

VB.Net Code to Get Time Difference:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If (IsPostBack = False) Then
            Dim dtFrom As DateTime
            Dim dtTo As DateTime
            Dim sFrom As String = "10:35:00"
            Dim sTo As String = "12:50:00"
            If DateTime.TryParse(sFrom, dtFrom) AndAlso DateTime.TryParse(sTo, dtTo) Then
                Dim tSpan As TimeSpan = dtTo - dtFrom
                Dim nDay As Integer = tSpan.Days
                Dim nHour As Integer = tSpan.Hours
                Dim nMin As Integer = tSpan.Minutes
                Dim nSec As Integer = tSpan.Seconds
                Dim sTimeDiff As String = (nDay.ToString("00") & ":") + ((nHour.ToString("00") & ":") + nMin.ToString("00") & ":") + nSec.ToString("00")
                Response.Write(sTimeDiff) 'output format 00:02:15:00
            End If
        End If
    End Sub

Hope now you can get Time Difference between two DateTime or Date Time.

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code