I need code to check any time in C # in HHMMSS format

Please help me find the verification code at any time in C #. format-HHMMSS

0
source share
2 answers

The easiest way is to use DateTime.TryParseExact:

DateTime time;
bool valid = DateTime.TryParseExact(text,
                                    "HHmmss",
                                    CultureInfo.InvariantCulture,
                                    DateTimeStyles.None,
                                    out time);

Note that “M” is months, while “m” is minutes and “s” are seconds; "HH" is a clock in a 24-hour clock instead of an "hh" that will use a 12-hour clock (usually with the am / pm indicator elsewhere).

DateTimeStyles.Nonesays it uses default options. This will use today's date as the date for the time. You can specify DateTimeStyles.NoCurrentDateDefaultwhich January 1 will use 1AD instead.

valid - false, time DateTime.MinValue.


, .NET 4, - TimeSpan.TryParseExact:

TimeSpan time;
bool valid = TimeSpan.TryParseExact(text,
                                    "hhmmss",
                                    CultureInfo.InvariantCulture,
                                    out time);

"hh" "HH" . . Custom TimeSpan format MSDN, , .NET 4.

+6

DateTime.TryParseExact

static bool IsTimeValid(string time)
{
  DateTime dt;

  return DateTime.TryParseExact(time, "HHmmss", 
    System.Globalization.CultureInfo.InvariantCulture, 
    System.Globalization.DateTimeStyles.None, out dt);
}
+2

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


All Articles