Menu ▼



Posted By :
avatarmrkraju
Total Views : 429

Get number of days difference between two dates

This example shows you how to get the number of days difference between two given dates using C# in asp.net

Using datetime subtract method we can get the timespan between two days, and timespan.TotalDays will give you the total number of days difference between the given days.

Example
days between two days

CS Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnDifference_Click(object sender, EventArgs e)
    {
        DateTime dt1 = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
        DateTime dt2 = DateTime.ParseExact(txtDate2.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
        TimeSpan tspan = dt2.Subtract(dt1);
        lblMessage.Text = "Number of days difference is: " + ((int)tspan.TotalDays).ToString();
    }

}

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Date 1:
        <asp:TextBox ID="txtDate1" runat="server" Text="11/09/2015"></asp:TextBox>
        <br />
        <br />
        Date 2:
        <asp:TextBox ID="txtDate2" runat="server" Text="11/22/2015"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnDifference" runat="server" Text="Get Difference" OnClick="btnDifference_Click" />
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Style="color: Green; font-weight: bold;"></asp:Label>
    </div>
    </form>
</body>
</html>






comments powered by Disqus


Search dotnetlearners.com