Sunday, July 29, 2012

Compare Dateime Difference in ASP.Net Example





 Design View:-

  <body>
    <form id="form1" runat="server">
    <div>
      <asp:Label ID="Label3" runat="server" Text="DataBase Date :"></asp:Label>
      <asp:Label ID="Label4" runat="server" ></asp:Label>
        <asp:Label ID="Label1" runat="server" Text="Select A Date :"></asp:Label>
     <asp:TextBox ID="TxtDate" runat="server"></asp:TextBox>
        <asp:ImageButton ID="ImaCalender" runat="server"
            ImageUrl="~/Images/Calender.jpg" Height="20px" Width="20px"
            onclick="ImaCalender_Click"/>
                <asp:Calendar ID="Calendar1"
                    runat="server" Visible="False" onselectionchanged="Calendar1_SelectionChanged"
                    ></asp:Calendar>
                <asp:Button ID="ButnComprasion" runat="server" Text="Compare"
            onclick="ButnComprasion_Click" /><br />
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>




  C# Code :-

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

public partial class Projects_Others_DateDifferencet : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader dr; 
    DateTime getdate;
    static DateTime  selectedDate;
    protected void Page_Load(object sender, EventArgs e)
    {      
            try
            {

                con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
                con.Open();
                cmd = new SqlCommand("select convert(varchar(20),date_of_signing,111) as date_of_signing from ufms.fms_companyInfo", con);
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    getdate = Convert.ToDateTime(dr["date_of_signing"].ToString());
                    Label4.Text = getdate.ToString("dd/MM/yyyy");
                }

                con.Close();
            }
            catch (Exception ex)
            {

            }
      
    }
    protected void ImaCalender_Click(object sender, ImageClickEventArgs e)
    {
        Calendar1.Visible = true;
    }
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        TxtDate.Text = Calendar1.SelectedDate.ToString("dd/MM/yyyy");
        selectedDate =Convert.ToDateTime( Calendar1.SelectedDate.ToString("MM/dd/yyyy"));
        Calendar1.Visible = false;
    }
    protected void ButnComprasion_Click(object sender, EventArgs e)
    {
        TimeSpan diff = getdate - selectedDate;
        if (diff.Days <= 0)
        {
            Label2.Text = "Please select valid date";
        }
        else
        {
            Label2.Text = "You have " + diff.Days + " days less from DataBase Date";
        }

    }
}

No comments:

Post a Comment