Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to parse dates in binder

Is it good approach in the model binder use the code like this:

TryParseDate(result.AttemptedValue, format, out parsedDate) 

And then "format" is a variable with different (customer specific) date format. Like 12/31/2013 or 31.12.2013 or other ones.

I have big problem with the format binding because if user puts the date with only 1 digit like: 1/1/2014 it will not parse because in the "format" value allowed formats: dd/MM/yyyy I know that it is possible to resolve by replacing this format to d/M/yyyy and then it works for both case, but is it good approach or it is dangerous?

Thank you in advance!

like image 567
Sergey Avatar asked Jul 10 '13 07:07

Sergey


1 Answers

I would recommend leaving the default model binder to do its work, it does a pretty good job of it and will deal with localization issues (ie. different date formats for different locales) for you.

Consider that there will always be restrictions on how a user can enter a date (you don't allow them to enter yyyy-MM-dd for example, even though it is a valid date format). Your custom binder code won't change that because it supplies a format.

I'd suggest that your goal should be to permit users to enter dates in the format that would be most usual for them (eg. dd/MM/yyyy in UK or Spain, MM/dd/yyyy in US etc). That will deal with the majority of cases. If you need to cater for users in different locales, the default model binder will do it all for you, so long as you set the thread culture for the user session:

string cultureCode = "en-GB";    //retrieve eg. from user profile
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureCode)

If you want to help users who are inputting dates in other formats, simply put a hint on your page that explains the expected format.

If you really must accept multiple formats per locale, you will need to write a custom model binder, and might want to try passing an array of acceptable formats to it for each locale that you deal with.

like image 102
Paul Taylor Avatar answered Sep 21 '22 14:09

Paul Taylor