How to do C # time check in HHMMSS format

The output of this code will always be false, even if I give the date in the correct format. Please help me ... Here 2 parameters passed are time and format, i.e. (Format "HHMMSS").

    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;
        }
    }
+3
source share
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 must use the format string "HHmmss" to check the 24-hour time.

Custom Date and Time Format Strings (MSDN)

+10
source

The following code works. You will have to slightly modify and add 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.
}
+2
source

Source: https://habr.com/ru/post/1785843/


All Articles