如何以HHMMSS格式执行c#时间validation

即使我以正确的格式传递日期,此代码的输出也将始终为false。请帮助我…这里传递的2个参数是时间和格式,即(“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; } } 

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

请记住,您应该使用“HHmmss”格式字符串来validation24小时的时间。

自定义日期和时间格式字符串(MSDN)

以下代码有效。 你需要调整一下并添加方法签名。

 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. }