Time validation in c#
We have a generic search text box and user can search any thing. I need to validate DateTime and particularly time part and user can enter any thing
docdate eq 1/1/2000 33:28:00 docdate eq 1/1/2000 13:28am In the above queries I need to validate date part knowing the c开发者_高级运维olumn docdate is valid date. What could be best way to achieve this.You can use DateTime.TryParse like this to convert from military time.
DateTime parsedDate;
DateTime.TryParseExact("1/1/2000 3:28:00", "M/d/yyyy H:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out d);
Play around with the format string (the 2nd parameter) to test various possible formats (for example: with and without am/pm, with and without milliseconds...)
Sounds like DateTime.TryParse is what you're looking for.
It will attempt to parse a date (returning true if valid, false if not), and provide a System.DateTime value if successful. One of the overloads lets you specify the specific formats you'd like to support.
The TryParse method is preferable to string parsing / regular expressions because it:
- Handles the various date / time rules (number of days per month, leap years, etc) and formats for multiple cultures
- Supports all date / time values that can be represented by a System.DateTime object
- Provides a System.DateTime object for valid dates, which is likely needed elsewhere in your code
You can use RegularValidation. You can find the appropriate expression from here
(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(?<sep>[/.-])(?<month>0?[1-9]|1[012])\2(?<year>(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)
精彩评论