Determine if a String is a valid date before parsing

后端 未结 12 1678
半阙折子戏
半阙折子戏 2020-12-03 11:36

I have this situation where I am reading about 130K records containing dates stored as String fields. Some records contain blanks (nulls), some contain strings like this: \'

12条回答
  •  Happy的楠姐
    2020-12-03 11:58

    You can take advantage of regular expressions to determine which format the string is in, and whether it matches any valid format. Something like this (not tested):

    (Oops, I wrote this in C# before checking to see what language you were using.)

    Regex test = new Regex(@"^(?:(?\d{2}-[a-zA-Z]{3}-\d{2})|(?\d{2}/\d{2}/\d{3}))$", RegexOption.Compiled);
    Match match = test.Match(yourString);
    if (match.Success)
    {
        if (!string.IsNullOrEmpty(match.Groups["formatA"]))
        {
            // Use format A.
        }
        else if (!string.IsNullOrEmpty(match.Groups["formatB"]))
        {
            // Use format B.
        }
        ...
    }
    

提交回复
热议问题