How to validate the DateTime of MM/dd/yyyy hh:mm format?

前端 未结 5 1753
无人及你
无人及你 2021-01-06 20:25

I am using MaskedEditExtender for entering a datetime. I am unable to figure out how to validate it.

Is there any Regular Expression for validating dates along with

5条回答
  •  执笔经年
    2021-01-06 20:52

    Use DateTime.Parse or DateTime.TryParse (there are also ParseExact and TryParseExact equivalents).

    If the string does not represent a valid DateTime it will not parse.

    DateTime myDateTime = DateTime.ParseExact(myString, 
                                              "MM/dd/yyyy hh:mm", 
                                              CultureInfo.InvariantCulture);
    

    The above will throw an exception if the value is not parseable. Use the Try variant if you want to avoid the chance of the exception being thrown - this requires an out parameter and testing the return value of the function for success.

提交回复
热议问题