Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all,

I have a date in textbox which is in the format of dd/mm/yyyy
when i try to convert this datetime to datetime

i mean
C#
DateTime dt=Convert.ToDateTime(txtDate.text);

it throws me error
HTML
Format Exception was Unhandled by user code
String was not recognised as valid datetime

my textbox has date as 21/10/2013
C#
DateTime dt = Convert.ToDateTime(txtRStartDate.Text);
      DateTime dtChanged = dt.AddYears(1);
      dtChanged = dtChanged.AddDays(-1);
      txtREDate.Text = Convert.ToString(dtChanged);

It throws me error invalid format exception

any SOlutions. plz..
Regards,
SUNIL MALI.
Posted
Updated 25-May-13 22:20pm
v4

Use ParseExact, or TryParseExact:

C#
DateTime dt;
if (DateTime.TryParseExact(dateStrignFromUser, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
   {
   // OK, use it.
   }
else
   {
   // Report problem to user
   }
 
Share this answer
 
Hello SUNIL MALI,

This kind of issue will arise, if your system (server if it is web app/where this app running), Date Time format is different from your coding format, it may like MM/dd/YY, chekc this
Modify that to dd/MM/yyyy as your format is like this 21/10/2013, then you can get this work

then User following

C#
DateTime dt = DateTime.Parse(txtRStartDate.Text);
        DateTime dtChanged = dt.AddYears(1);
        dtChanged = dtChanged.AddDays(-1);
        txtREDate.Text = Convert.ToString(dtChanged);


Thanks
Happy Coding
 
Share this answer
 
v2
you can get idea from this...



IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
String datetime = TextBox1.Text.Trim();
DateTime dt = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
Response.Write(dt.Date.ToString());
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900