【问题标题】:Checking Date format from a string in C#从 C# 中的字符串检查日期格式
【发布时间】:2013-10-01 22:02:50
【问题描述】:

我想检查string 是否包含dd/MM/yyyy 格式的1/01/200010/01/2000 等日期。

到目前为止,我已经尝试过了。

DateTime dDate = DateTime.Parse(inputString);
string.Format("{0:d/MM/yyyy}", dDate); 

但是如何检查该格式是否对throw an exception 正确?

【问题讨论】:

    标签: c# string date time


    【解决方案1】:
    string inputString = "2000-02-02";
    DateTime dDate;
    
    if (DateTime.TryParse(inputString, out dDate))
    {
        String.Format("{0:d/MM/yyyy}", dDate); 
    }
    else
    {
        Console.WriteLine("Invalid"); // <-- Control flow goes here
    }
    

    【讨论】:

      【解决方案2】:

      您可以将DateTime.ParseExact 与格式字符串一起使用

      DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);
      

      如果给定的字符串不是给定的格式,上面将抛出异常。

      如果格式不正确不需要异常,则使用DateTime.TryParseExact,但可以检查该方法的返回值来确定解析值是否成功。

      查看Custom Date and Time Format Strings

      【讨论】:

      • 但它还会检查single digit 的日期,例如day1/01/2000
      • 你决定你需要把什么作为日期时间格式字符串,d 只表示没有前导零,dd 表示它将在单日值之前添加零,如果你有多个有效日期时间格式最好使用DateTime.ParseExact 的一种重载方法,它接受多种日期时间格式
      【解决方案3】:

      我认为解决方案之一是使用 DateTime.ParseExact 或 DateTime.TryParseExact

      DateTime.ParseExact(dateString, format, provider);
      

      来源:http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

      【讨论】:

      • 这也增加了时间。上午 12 点
      【解决方案4】:

      你可以在下面使用IsValidDate():

       public static bool IsValidDate(string value, string[] dateFormats)
          {
              DateTime tempDate;
              bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
              if (validDate)
                  return true;
              else
                  return false;
          }
      

      您可以传入值和日期格式。例如:

      var data = "02-08-2019";
      var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
      
      if (IsValidDate(data, dateFormats))
      {
          //Do something
      }
      else
      {
          //Do something else
      }
      

      【讨论】:

      • 对我来说,这看起来像是对 OP 原始问题的更相关的答案,因为您可以指定显示日期的形式。我还没有实现这一点,但它确实表明这实际上应该是正确的答案。
      • 你肯定会在以下行得到一个错误:var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
      【解决方案5】:

      https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx

      string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                           "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                           "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                           "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                           "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
        string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM", 
                                "5/1/2009 6:32:00", "05/01/2009 06:32", 
                                "05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"}; 
        DateTime dateValue;
      
        foreach (string dateString in dateStrings)
        {
           if (DateTime.TryParseExact(dateString, formats, 
                                      new CultureInfo("en-US"), 
                                      DateTimeStyles.None, 
                                      out dateValue))
              Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
           else
              Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
        }
      

      【讨论】:

        【解决方案6】:

        你总是可以尝试:

        Regex r = new Regex(@"\d{2}/\d{2}/\d{4}");
        
        r.isMatch(inputString);
        

        这将检查字符串的格式是否为“02/02/2002” 如果你想确保它是像 dd/mm/yyyy 这样的有效日期,你可能需要更多的时间

        【讨论】:

        • 请在回答时提供解释
        【解决方案7】:

        使用有效日期格式的数组,检查docs

        string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
        DateTime parsedDate;
        var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);
        
        if(isValidFormat)
        {
            string.Format("{0:d/MM/yyyy}", parsedDate);
        }
        else
        {
            // maybe throw an Exception
        }
        

        【讨论】:

          【解决方案8】:

          试试这个

          DateTime dDate;
          dDate = DateTime.TryParse(inputString);
          String.Format("{0:d/MM/yyyy}", dDate); 
          

          查看此链接了解更多信息。 http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

          【讨论】:

          • DateTime.TryParse 没有将两个参数作为参数的重载
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-04-26
          • 2011-10-29
          • 2011-10-06
          • 1970-01-01
          • 2022-01-13
          • 1970-01-01
          相关资源
          最近更新 更多