Robin
Robin

Reputation: 471

Datetime format problems in iis Asp.net

I have got two TextBoxes(txtdateofissue and txtdateofexpiry).The First Textbox is Attached with a CalendarExtender control. I want that if a user selects a date for the txtdateofissue textbox then automatically the same date but next year should get entered in txtdateofexpiry textbox. Date Should be in dd-MM-yyyy format i.e. 24-04-2013. i have written a code for this but i am getting an error (String is not a valid datetime format)

my code:

protected void txtdateofIssue_TextChanged(object sender, EventArgs e)
        {
            DateTime dt = Convert.ToDateTime(txtdateofIssue.Text);
            dt = dt.AddDays(-1).AddYears(1);
            txtdateofExpiry.Text = dt.ToShortDateString();
        }

the first line in which i declare datetime variable dt throws up the error (String is not a valid datetime format)

when i run this code in my local machine it works fine but if i run it on iis then it shows errors...please either correct my code or guide me in a new way...thanks in advance...

Upvotes: 1

Views: 1713

Answers (1)

Damith
Damith

Reputation: 63065

you can use DateTime.TryParseExact method

DateTime dt;
if (DateTime.TryParseExact(txtdateofIssue.Text, "dd-MM-yyyy",
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None,
                           out dt))
{
   dt = dt.AddDays(-1).AddYears(1);
   txtdateofExpiry.Text = dt.ToString("dd-MM-yyyy");
}

To convert Date Time back to given format

Look at the docs for custom date and time format strings for more info.

Upvotes: 2

Related Questions