Vikas
Vikas

Reputation: 17

How to Get 3 days before date if get date from database?

I have a Form where the user fills information about XYZ , with start date and expiry date.when clicking on the button , the information will save in database. Now I need 3 days before date from the expiry date and need show in the label on a web form ex. the expiry date is 12/12/2012 this date is saved in the database now when the user open his profile there must show expiry date 09/12/2012

I get 3 days before date from current date but not have any idea that how get if the date has come from the database any idea?

you can see in codes in lbltest i show 3 day before date from current date and Label1 get date from database

SqlCommand cmd = new SqlCommand("Select Enddate from moudetails", con);
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DataTable Dt = new DataTable();
DA.Fill(Dt);
if (Dt.Rows.Count > 0)
{
    lbltest.Text = DateTime.Now.AddDays(-3).ToString("dd/MM/yyyy");
    Label1.Text = Dt.Rows[0]["Enddate"].ToString();                
}

Upvotes: 2

Views: 2322

Answers (3)

You can use System.Convert

string dateString = Dt.Rows[0]["Enddate"].ToString();
DateTime date = Convert.ToDateTime(dateString);

date.AddDays(-3).ToString();

Upvotes: 1

iSpain17
iSpain17

Reputation: 3053

If you store dates as string, try using the DateTime.ParseExact method. Then you will be able to deduct the three days from the date retrieved from database.

Based on comments, another solution that might work is casting the object to datetime:

Label1.Text = (Dt.Rows[0]["Enddate"] as DateTime).ToString()

Upvotes: 2

Vikas
Vikas

Reputation: 17

I use this method suggested by Sir, ISPain17

 SqlCommand cmd = new SqlCommand("Select Enddate from moudetails", con);
    SqlDataAdapter DA = new SqlDataAdapter(cmd);
    DataTable Dt = new DataTable();
    DA.Fill(Dt);
    if (Dt.Rows.Count > 0)
    {
        string dateString = Dt.Rows[0]["Enddate"].ToString();
        //lbltest.Text = DateTime.Now.AddDays(-3).ToString("dd/MM/yyyy");
        //Label1.Text = Dt.Rows[0]["Enddate"].ToString();
        Label1.Text = DateTime.Parse(dateString).AddDays(-3).ToString();
    }

and its work :D

Upvotes: 0

Related Questions