String contains only a given set of characters

前端 未结 7 1487
执笔经年
执笔经年 2021-02-18 13:22

I need to know if a given string is a valid DateTime format string because the string may represent other things. I tried DateTime.ParseExact(somedate.ToString(format), format)

7条回答
  •  长发绾君心
    2021-02-18 13:49

    Slightly shorted Dan Tao's version since string represents an implementation of IEnumerable<&char>

       [TestClass]
       public class UnitTest1 {
          private HashSet _legalChars = new HashSet("yYmMdDsShH".ToCharArray());
    
          public bool IsPossibleDateTimeFormat(string format) {
             if (string.IsNullOrEmpty(format))
                return false; // or whatever makes sense to you
             return !format.Except(_legalChars).Any();
          }
    
          [TestMethod]
          public void TestMethod1() {
             bool result = IsPossibleDateTimeFormat("yydD");
             result = IsPossibleDateTimeFormat("abc");
          }
       }
    

提交回复
热议问题