String contains only a given set of characters

前端 未结 7 1462
执笔经年
执笔经年 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 14:04

    I'd just do this:

    public static class DateTimeFormatHelper
    {
        // using a Dictionary<char, byte> instead of a HashSet<char>
        // since you said you're using .NET 2.0
        private static Dictionary<char, byte> _legalChars;
    
        static DateTimeFormatHelper()
        {
            _legalChars = new Dictionary<char, byte>();
            foreach (char legalChar in "yYmMdDsShH")
            {
                _legalChars.Add(legalChar, 0);
            }
        }
    
        public static bool IsPossibleDateTimeFormat(string format)
        {
            if (string.IsNullOrEmpty(format))
                return false; // or whatever makes sense to you
    
            foreach (char c in format)
            {
                if (!_legalChars.ContainsKey(c))
                    return false;
            }
    
            return true;
        }
    }
    

    Of course, this might be an excessively strict definition, as it rules out what most people would consider valid formats such as "yyyy-MM-dd" (since that includes "-" characters).

    Determining exactly what characters you wish to allow is your judgment call.

    0 讨论(0)
提交回复
热议问题