Wednesday, 16 January 2013

DIFFERENCE BETWEEN TWO DATE

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:
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:
Protected Sub Page_Load(ByVal sender As Object, ByVal 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

No comments:

Post a Comment

Note: only a member of this blog may post a comment.