Question

I have several forms within my MVC app that have date values which are chosen via a datepicker tool. This works well when debugging locally but on deployment to the cloud environment my dates are not being correctly converted. I have the following code:

string[] uploaddate = form.GetValues("uploaddate");
string[] expirydate = form.GetValues("expirydate");

This gets the date as 31/08/2013 etc. and from here I was converting to DateTime as follows:

Convert.ToDateTime(uploaddate[0]);
Convert.ToDateTime(expirydate[0]);

When I deploy to the Azure server I receive the following error:

String was not recognized as a valid DateTime.

I think that the instance image has a culture of US while my application was designed in UK format. How can I get around this problem so that the information is saved to the database regardless of the culture of the user?

Was it helpful?

Solution 2

I'd improve the date picker so that the value it posts back is always yyyy-MM-dd but displays in whichever culture you care about. This makes the problem a client problem, not a server one (which it is really)

UPDATE

I've done some investigation Convert.ToDateTime() simply calls DateTime.Parse with the current culture settings. I've just checked one of my VMs and it runs with US local settings which is why your're getting the error you are with d/M/y. I would standarise the format of the date that is being sent to the server (it doesn't really matter to which format, but I'm always a fan of YMD) and then use DateTime.TryParseExact() that @No One mentions, but with just one format.

OTHER TIPS

you should use DateTime.TryParseExact. You can specify all the possible formats and it won't throw exception either.

Example from MSDN.

string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                        "5/1/2009 6:32:00", "05/01/2009 06:32", 
                        "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
DateTime dateValue;

foreach (string dateString in dateStrings)
{
   if (DateTime.TryParseExact(dateString, formats, 
                              new CultureInfo("en-US"), 
                              DateTimeStyles.None, 
                              out dateValue))
      Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
   else
      Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}

You can use the overload of Convert.ToDateTime which allows you to specify a culture. This will allow you to force it to always use UK culture if that is your requirements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top