如何验证日期时间输入是否符合ISO 8601标准

3
我尝试验证输入,然后可以得到我想要的输入。
例如:
if (string != validate(string)) 
       then not valid
else 
       then valid

输入和期望输出

2017-03-17T09:44:18.000+07:00 == valid

2017-03-17 09:44:18 == not valid

@PrasadTelkikar 更新完成 - Christopher
3个回答

6

要检查有效的 DateTime,你需要正确的 DateTime 格式(例如 "yyyy-MM-ddTHH:mm:ss.fffzzz"),并使用 DateTime.TryParseExact() 来验证您的日期时间字符串,

尝试使用下面的代码来验证您的日期时间字符串:

 public void ValidateDateTimeString(string datetime)
 {
        DateTime result = new DateTime(); //If Parsing succeed, it will store date in result variable.
        if(DateTime.TryParseExact(datetime, "yyyy-MM-ddTHH:mm:ss.fffzzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
            Console.WriteLine("Valid date String");
        else
            Console.WriteLine("Invalid date string");
 }

Try it online


1
你应该可以使用DateTime.TryParseExact。它将根据解析是否正确返回true/false。你可以使用format参数指定要匹配的模式。

如果使用这个格式"2017-03-17T09:44:18.000+07:00",我需要使用什么格式? - Christopher

0
你可以使用正则表达式来匹配你想要的日期格式(参考this example,了解你所需格式的正则表达式应该是什么样的)。
function Validate(string Input)
{
   System.Text.RegularExpressions.Regex MyRegex = new 
   System.Text.RegularExpressions.Regex("([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))");
   return MyRegex.Match(Input).Success // returns true or false
}

如果使用这种格式"2017-03-17T09:44:18.000+07:00",我需要使用什么正则表达式? - Christopher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接