ASP.NET MVC DateTime manual input conversion best practice - c#

I have ASP.NET MVC site with ordinary Html Form with text field to put Date in.
<input type="textbox" name="date"/>
Controller method looks like:
void DoSomething(DateTime date)
{
....
}
As users have different locales and habits how to enter date how shall I handle DateTime formats? I guess there should be code that try to parse string to several date time formats. Can I handle all DateTime(s) params centralized without Helper class call every time controller expects DateTime ? How can I take into account user locale ?
Thank you in advance!

You can use jQuery UI datepicker for example, and set the format. This will also be a better user experience then a simple textbox..
$('#datetime').datepicker({ format: 'yy-mm-dd hh:ii' });
Datepicker provides support for localizing its content to cater for
different languages and date formats.

Best practice here is to force users to enter only one date format.
You can achieve this with RegularExpression validation and date picker such as JQuery Datepicker.
UPDATE :
Also, if you not want to force users to one format, please check DateTime.Parse method of C# but it is a little tricky and you need to be careful while using it. There might be some conflicts. (E.g. 2011-01-01 can be seen as two different dates if you don't know the format.)

If you try to handle every type of formats you will have to provide the type of the format.
Issue that is commonly faced is mm-dd-yy and dd-mm-yy format say 02-01-11. Question is is it 2 Jan or 1 Feb.
If you are able to send the correct format type there shouldn't be any problem other than the input string could be wrong itself.
The best solution (which you may not be looking for) is to validate date/time while user inputs in the form. Like making separate drop down box(or just text box) for date and month.

Related

Parse date when format is not constant c#

normally i parse date like this way
DateTime.Parse()
DateTime.ParseExact()
i am in situation where user run exe and pass date as argument. so user can give date with various format like
dd/MM/yyyy
MM/dd/yyyy
dd-MM-yyyy
MM-dd-yyyy
yyyyMMdd
so i have to parse that date. when date format is yyyyMMdd then i am parisng date like this way DateTime.ParseExact(this.enddate, "yyyyMMdd", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
so guide me what code i should write to parse date which work for any date format. thanks
I would recommend that you standardize on a single format. Otherwise you will run into ambiguous dates in cases where you have dates that can be parsed by different formats, but represent different dates in both
Ex:
dd-MM-yyyy
MM-dd-yyyy
what code i should write to parse date which work for any date format
As a technical answer, you can pass multiple formats to DateTime.TryParseExact() via a string array containing all acceptable formats.
Practically, though, the others have already pointed out that there is no way to tell the difference between months and days when the format isn't strictly enforced.
One possible solution is to have the user pass the date in as three separate arguments, each flagged with some kind of indicator such as /y2013 /m11 /d12 or maybe y:2013 m:11 d:12. You can even mash them together like /y2013/m11/d12. Then you can use Regular Expressions to parse out the parts, or even just plain old string manipulation.
There's no built in way to parse dates which work for ANY format. However, you can quite easily define your own format using DateTimeFormatInfo, letting you convert more or less any format to a proper date, as long as you know the format ahead of time.
In every major website you enter the date using comboboxes for day/month/year
or some datetime widget. So I don't see a reason to use a textbox. If you really
need to, add a tooltip or a watermark with the predefined format and force the
user to it.

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!
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.

Javascript equivalent to .NET's DateTime.Parse

I'm trying to build a validator that will work with .NET's DefaultModelBinder of using DateTime.Parse to convert a string from the form post to a DateTime. I don't want to have to wait until a date has been posted to the server for it to realize it was a bad date.
Currently jquery.validate uses the following code to validate date fields:
// http://docs.jquery.com/Plugins/Validation/Methods/date
date: function(value, element) {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}
However, due to Javascript's terrible Date parser, this:
275481/69/100089
Will evaluate as valid, to Sep. 12, 275760.
While on the other hand, this:
11-19-2013
Will evaluate as invalid.
Of course, I understand that C#'s DateTime.Parse() takes things like culture (localization) and leap year into account, and I could live with assuming a fixed (US) culture, and allowing "02-29-2013" on the client and kick it out at the server (ideally not, but it's acceptable).
But I can't believe someone hasn't put together a better date validator to work with C#'s DateTime.Parse() logic.
Maybe someone has, I just haven't found it -- which is why I'm posting here.
And I know I have several ways to go about this -- from incredibly simple (less accurate) to incredibly complex (more accurate), but I'm hoping someone has already gone down this road and found the sweet spot.
Datejs seems pretty robust to me. Its parse function supports over 150 cultures:
Date.parse("February 20th 1973")
And in case you need to parse a date string that is not valid in the current culture you can use the parseExact function:
// The Date of 15-Oct-2004
Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]);
In all honesty, your best bet is to perform an AJAX hit, and ask your ASP.net web-server to parse the string and return a Javascript date.
Javascript libraries easily get confused with different locales, e.g.:
GET /ParseDate.ashx?dateStaring=06/01/34 4:53:05 غ.و&locale=ar-SA
Which gets really complicated because:
"6/1/34" = November 19, 2012
The .NET framework, with Windows behind it, has support for a lot of different locales.
Instead of trying to find two Datetime implementations (one for JS and another for C#) that have similar validation and parsing, have you considered having the client 1)use its own library to validate the date and 2)parse and reformat the date to a C# friendly format?
This would allow you to use DateJS to get a very flexible front end for date inputs, make it easier to deal with the client side culture, and let your server side deal with a fixed format.
Have you tried passing your string into the constructor?
Here's a sample from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
var birthday = new Date("December 17, 1995 03:24:00");

How to validate string is correct date time

I have some data picked up from an excel file.
I want to validate that the user has entered a valid date time string. I have tried to use DateTime.Parse method but found that certain values seem to be accepted.
For example,
If I submit 3.3 as a date time this is accepted by the DateTime.Parse method as a valid date time and outputs 03/03/2012 00:00:00
I want to want to block this. Only allowing the user to enter correctly formatted date times.
So for example a user could supply 03/03/2012 or 03/03/2012 12:30:00 but not values like 01022012 or 3.3.2012
Any Ideas?
You want to use DateTime.ParseExact or DateTime.TryParseExact
This allows you do parse from a date format string of your choice.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx
Examples here:-
http://msdn.microsoft.com/en-us/library/ms131044.aspx
You can use RegEx to to this. Something like this should help #"\d{2}/\d{2}/\d{4}(\s+\d{2}\:\d{2}\:\d{2})?"
You can handle it on the client side with various jquery plugin/functions like this or a simple Google search can return many other useful results.
if you want to handle it on the server side, (I am not sure on what project you are working) but depending over it you can write your own method/use Regex or Data Annotation MVC.
If you are still having trouble try adding few details about your project such as Language, Architecture etc. that would help more in providing the right solution.
Hope it helps. Thankyou

Localized Date Validator

Is there a way to use user's culture to localize the Range Validator for date? I am looking for a good way to validate date and avoiding to provide a fix format (e.g.: do a dd/mm/yyyy using Regular Expression Validator)
Use the Date.TryParseExact() method, consulting the documentation.
Use members of the returned My.Application.Culture.CurrentCulture.DateTimeFormat object, which is of class System.Globalization.DateTimeFormatInfo, to retrieve the date formats for the current culture (there are several formats for every culture, such as long format and short format...).
This will be something closest to what I want actually.
Getting user's language preference based on language settings:
userLanguage = Request.UserLanguages[0];
Get ShortDatePattern base on language:
new CultureInfo(userLanguage).DateTimeFormat.ShortDatePattern;
From here I will use the pattern to validate user's input and to display the required format on the page.

Categories