简体   繁体   English

ASP.NET MVC DateTime手动输入转换最佳实践

[英]ASP.NET MVC DateTime manual input conversion best practice

I have ASP.NET MVC site with ordinary Html Form with text field to put Date in. 我有带有普通HTML表单的ASP.NET MVC网站,带有文本字段,可将Date放入。

<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? 由于用户具有不同的区域设置和习惯,因此如何输入日期,我应如何处理DateTime格式? 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 ? 我可以在每次控制器期望DateTime时都集中处理所有DateTime参数而无需Helper类调用的情况吗? How can I take into account user locale ? 如何考虑用户的语言环境?

Thank you in advance! 先感谢您!

You can use jQuery UI datepicker for example, and set the format. 例如,您可以使用jQuery UI datepicker ,并设置格式。 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. Datepicker为本地化内容提供支持,以适应不同的语言和日期格式。

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 . 您可以使用RegularExpression验证和日期选择器(例如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. 另外,如果您不想强制用户使用一种格式,请检查C#的DateTime.Parse方法,但这有点棘手,在使用它时需要小心。 There might be some conflicts. 可能会有一些冲突。 (Eg 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. 通常面临的问题是mm-dd-yy和dd-mm-yy格式,例如02-01-11。 Question is is it 2 Jan or 1 Feb. 问题是1月2日还是2月1日。

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. 就像为日期和月份制作单独的下拉框(或只是文本框)一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM