Link to home
Start Free TrialLog in
Avatar of madhanmss
madhanmss

asked on

Datetime validation in c# issue

Hi, I need to validate the date and time part separately. I am using the following function to determine the correct date and time.

private bool ValidateDateTime(string szDateTime, string szFormat)
        {
            try
            {
                   System.IFormatProvider format = new System.Globalization.CultureInfo("en-US", true);                  
                   return DateTime.TryParseExact(szDateTime, szFormat, format,  
                   System.Globalization.DateTimeStyles.AllowWhiteSpaces, out outDate);                
            }
            catch (Exception ex)
            {
               
            }
            return false;
        }

The inputs and validation results are given below.
1. ValidateDateTime("20081005","yyyyMMdd")  - Pass
2.ValidateDateTime("121212","hhmmss")  - Pass

But if i give the time as 13 like below, it fails.
3.ValidateDateTime("131212","hhmmss")  - Fail

Please let me know how to fix this issue as the time component can be between 0-23.

Regards,
Madhan
ASKER CERTIFIED SOLUTION
Avatar of philipjonathan
philipjonathan
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dmitry G
Try "HHmmss" formal, or "Hmmss" for time. Lower case "hh" is probably used for am/pm format like "hh:mm tt"
Ha-ha, 3 minutes late! :)