【问题标题】:How to validate DateFormat of specific culture without Time part如何在没有时间部分的情况下验证特定文化的 DateFormat
【发布时间】:2013-04-19 16:09:32
【问题描述】:

我需要使用 TryParse() 或 TryParseExact() 方法在所有文化日期验证用户输入。

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

此代码验证:

  • 01-10-2011
  • 2011 年 1 月 10 日
  • 01-10-2011 20:11
  • 01/10/2011 20:11

但我只需要它来验证:

  • 01-10-2011
  • 2011 年 1 月 10 日

连同指定文化中所有可能的日期格式:

  • 2011 年 1 月 10 日
    1. 2011 年 10 月

这些验证应该失败:

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

有什么想法吗?

谢谢。

【问题讨论】:

    标签: c# .net datetime cultureinfo tryparse


    【解决方案1】:
    DateTime.ParseExact(dateString, "d/MM/yyyy", DateTimeFormatInfo.InvariantInfo);
    

    dateString 是您的日期。

    【讨论】:

    • 这不是我想要的。我希望能够在某些文化中验证 所有可能的日期,例如“2011 年 1 月 10 日”、“2011 年 1 月 10 日”、“2011 年 1 月 10 日”、“1. oktober 2011' 等。您的解决方案只会验证一种模式。
    【解决方案2】:

    这可能会有所帮助,您可以将日期时间(带或不带时间)作为字符串提供并用 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();
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-17
      • 2021-02-10
      • 1970-01-01
      • 2011-04-18
      • 2011-03-01
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      相关资源
      最近更新 更多