0

I need to validate user input on all culture dates using TryParse() or TryParseExact() method.

DateTime.TryParse(args.Value, new CultureInfo("nl-NL", false), DateTimeStyles.None, out date)

This code validate:

  • 01-10-2011
  • 1-10-2011
  • 01-10-2011 20:11
  • 01/10/2011 20:11

But I need it to validate only:

  • 01-10-2011
  • 1-10-2011

Together with all possible date formats within specified culture:

  • 1/10/2011
    1. oktober 2011

And validation of these should fail:

  • 01-10-2011 20:11
  • 01/10/2011 20:11

Any idea?

Thanks.

mimo
  • 6,221
  • 7
  • 42
  • 50

2 Answers2

0
DateTime.ParseExact(dateString, "d/MM/yyyy", DateTimeFormatInfo.InvariantInfo);

Where dateString is your date.

misleadingTitle
  • 657
  • 6
  • 21
  • this is not exactly what I am looking for. I want to be able to validate **all possible dates** within some culture e.g. '1.10.2011', '1-10-2011', '1/10/2011', '1. oktober 2011', etc. Your solution will only validate one pattern. – mimo Apr 19 '13 at 21:43
0

this might help , you can provide the datetime ( with or without time) as string and wrap it with try catch for validation .

From 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();
      }
   }
}
aked
  • 5,625
  • 2
  • 28
  • 33