Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • String was not recognized as a valid DateTime

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 416
    Comment on it

    Hi,

    Many a times we encounter this issue where passing the correct date also ends up on this error, which makes it a bit complex and mind boggling.The main reason behind the error is the string passed as a date is not in the format the system needs.

    Let me explain this with a simple example. Lets suppose we are passing a string as "19/10/2016" and while converting it to a DateTime variable like:

    string strDate = "19/10/2016";
    DateTime date = convert.ToDateTime(strDate);

    How many of us think that this absolutely correct looking piece of code can gives a runtime error. If your answer is "No", then you are wrong. Have you ever thought if your system's date format is configured as "MM/dd/yyyy".

    This case occurs when we move our code from our local developer machine to production, we might not know the date format there. So, if the developer machine or the production server machine has a date format as "MM/dd/yyyy", then the above correct looking piece of code will give you an error stating "String was not recognized as a valid DateTime".

    What will you do to resolve this as it already looks correct, you are passing a correct Date but just in a different format, if you think of changing the format then it will be a temporary solution and you will have to be pretty carefull at all times when you upload a new build. It seems to be a manual process. And as we are developers trying to automate many complex problems, will not like to be manually doing this everytime.

    So, the solution is pretty simple that will solve the issue from the root. What if we change the current culture. You can do this by three simple code lines:

    System.Globalization.CultureInfo customCulture = new System.Globalization.CultureInfo("en-US");
    customCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
    System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

    Here you can define what date format you want.

     

    And you are good to go.....

     

    Happy Coding.....

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: