Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to perform c# time validation in HHMMSS format

Output of this code will always be false,even if I pass date in correct format.Please help me... Here the 2 Parameters passed are time and format, ie("HHMMSS" format).

    static bool ValidateTime(string time, string format)
    {
        try
        {
            //time = time.Replace(":","");
            System.Globalization.DateTimeFormatInfo tinfo = new System.Globalization.DateTimeFormatInfo();

            tinfo.LongTimePattern = format;

            DateTime dt = DateTime.ParseExact(time, "format", tinfo);
            if (dt.Hour != null)
            {

            }
            return true;
        }
        catch (Exception e)
        {

            return false;
        }
    }
like image 338
user578104 Avatar asked Oct 22 '25 16:10

user578104


2 Answers

static bool ValidateTime(string time, string format)
{
    DateTime outTime;
    return DateTime.TryParseExact(time, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out outTime);
}

Remember that you should use "HHmmss" format string to validate 24-hour time.

Custom Date and Time Format Strings (MSDN)

like image 181
bniwredyc Avatar answered Oct 25 '25 07:10

bniwredyc


The following code works. You'll have to tweak a bit and add the method signatures.

string time = "201555";
string format = "HHmmss";
bool ok = false;

try
{
    System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
    DateTime dt = DateTime.ParseExact(time, format, provider);
    if (dt.Hour != null)
    {
        ok = true;
    }
}
catch (Exception e)
{
    //// ok = false; // already setup in initializer above.
}
like image 44
Divi Avatar answered Oct 25 '25 07:10

Divi