Datetime validation in c# issue

Posted on 2008-11-18
Last Modified: 2013-12-17
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)
                   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.

Question by:madhanmss
    LVL 18

    Accepted Solution

    Try changing the hh to HH:
    ValidateDateTime("131212", "HHmmss")
    LVL 29

    Expert Comment

    Try "HHmmss" formal, or "Hmmss" for time. Lower case "hh" is probably used for am/pm format like "hh:mm tt"
    LVL 29

    Expert Comment

    Ha-ha, 3 minutes late! :)

    Featured Post

    6 Surprising Benefits of Threat Intelligence

    All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

    Join & Write a Comment

    Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
    This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now