How To Get Number of Days or Date Difference between two Dates in Asp.Net C# VB.Net

In case of date time calculation from front end we need to find out the days difference between two given dates by user. Dates may come from dtpicker or from calendar control whatever we will use, Asp.Net provide us built in subtract method to identify the number of days or date difference between two dates. In this article i will show you, How to identify datediff between two dates in both C# and Vb.Net front end Language.

C# Code to Get Date Difference:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            DateTime dTFrom;
            DateTime dTo;
            string sFrom = "September 01, 2014";
            string sTo = "September 10, 2014";
            if (DateTime.TryParse(sFrom, out dTFrom) && DateTime.TryParse(sTo, out dTo))
                TimeSpan TS = dTo.Subtract(dTFrom);
                int days_Diff = TS.Days;
                Response.Write("Day diference between two dates: " + days_Diff.ToString());

VB.Net Code to Get Date Difference:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim dTFrom As DateTime
            Dim dTo As DateTime
            Dim sFrom As String = "September 01, 2014"
            Dim sTo As String = "September 10, 2014"
            If DateTime.TryParse(sFrom, dTFrom) AndAlso DateTime.TryParse(sTo, dTo) Then
                Dim TS As TimeSpan = dTo.Subtract(dTFrom)
                Dim days_Diff As Integer = TS.Days
                Response.Write("Day diference between two dates: " + days_Diff.ToString())
            End If
        End If
    End Sub

Date Difference Asp.Net C# VB.Net

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