String was not recognised as a valid datetime

String was not recognised as a valid datetime


 String was not recognised as a valid datetime

 protected void Button1_Click(object sender, EventArgs e)
    {
        string FromDate = "31-12-2011";

        DateTime dt = DateTime.Parse( FromDate );
    }
 


The fromDate specified above is in DD-MM-YYYY UK format and the code current culture is in MM-DD-YYYY US format.
So, the code running at server was not able to recognise string specified in UK format.

Remarks: Use clientside regular expressions to validate date or Use Jquery Calendar control
              for accepting date in appropriate format which your server is set to recognize.

Set CurrentCulture property of thread to "en-GB", it will recognize the input string
in UK DD-MM-YYYY format.

 protected void Button1_Click(object sender, EventArgs e)
    {
        string FromDate = "31-12-2011";

        DateTime dt;      

        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

        CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;


        dt = DateTime.Parse(FromDate, ci);

        Response.Write( dt.ToShortDateString() );

    }

  Description: The current culture of the thread has been set to en-GB. It tells the server to recognise the string in UK MM-DD-YYYY format.

For more information about datetime culture visit below url

http://revenmerchantservices.com/post/c-datetime.aspx

 

Tags:

String was not recognised as a valid datetimeDateTimeTryParse using C# and VB.net exampleDateTime format Time StringC# Convert String To DateTimeString was not recognized as a valid BooleanC# Parse method of DateTime.net String vs stringAsp.net Convert String To ImageDateTime.Today Vs DateTime.NowReplace string in C#[C#] Remove Last Character From String

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.