我需要使用TryParse()或TryParseExact()方法验证所有文化日期的用户输入。
DateTime.TryParse(args.Value, new CultureInfo("nl-NL", false), DateTimeStyles.None, out date)
此代码验证:
但我需要它才能验证:
与指定文化中的所有可能日期格式一起使用:
验证这些应该失败:
有什么想法吗?
感谢。
答案 0 :(得分:0)
DateTime.ParseExact(dateString, "d/MM/yyyy", DateTimeFormatInfo.InvariantInfo);
其中dateString是您的日期。
答案 1 :(得分:0)
这可能会有所帮助,您可以将日期时间(有或没有时间)作为字符串提供,并使用try catch进行包装以进行验证。
来自MSDN - Convert.ToDateTime Method (String, IFormatProvider)
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
Console.WriteLine("{0,-18}{1,-12}{2}\n", "Date String", "Culture", "Result");
string[] cultureNames = { "en-US", "ru-RU","ja-JP" };
string[] dateStrings = { "01/02/09", "2009/02/03", "01/2009/03",
"01/02/2009", "21/02/09", "01/22/09",
"01/02/23" };
// Iterate each culture name in the array.
foreach (string cultureName in cultureNames)
{
CultureInfo culture = new CultureInfo(cultureName);
// Parse each date using the designated culture.
foreach (string dateStr in dateStrings)
{
DateTime dateTimeValue;
try {
dateTimeValue = Convert.ToDateTime(dateStr, culture);
// Display the date and time in a fixed format.
Console.WriteLine("{0,-18}{1,-12}{2:yyyy-MMM-dd}",
dateStr, cultureName, dateTimeValue);
}
catch (FormatException e) {
Console.WriteLine("{0,-18}{1,-12}{2}",
dateStr, cultureName, e.GetType().Name);
}
}
Console.WriteLine();
}
}
}