How to check a string in the form of YYYY-MM-DD (C #)

Most of the ways I've seen in SO have involved checking a C # date object, which I don't want to do. For what I'm working on, the user enters a string in the format, for example, 1999-02-23. I would like to confirm that the string entered matches the format YYYY-MM-DD. The solutions I came up with seem too complicated.

+4
source share
2 answers

Try

var stringToValidate = "1999-02-23";
DateTime dt;
bool ok = DateTime.TryParseExact(
   stringToValidate,
   "yyyy-MM-dd",
   CultureInfo.InvariantCulture,
   DateTimeStyles.None,
   out dt
);
+9
source

: @AlexD - . Regex, .

, :

, SO, # , , .

Regex, Regex:

FEB/APR/JUN/SEP/NOV DateTime DateTime.TryParseExact():

// single line Regex, formatted below for readability:
// "\d{3}[1-9]-(0[1-9]|1[012])-(0[1-9]|1\d|2\d|3[01])"
var regexSimple = new Regex(
    @"
        # DateTime.MinValue => '0001-01-01'
        \d{3}[1-9]
        - 
        (0[1-9] | 1[012])
        -
        (0[1-9] | 1\d | 2\d | 3[01])
    ",
    RegexOptions.Compiled
    | RegexOptions.IgnorePatternWhitespace
);

FEB DateTime DateTime.TryParseExact() :

// single line Regex, formatted below for readability:
// "\d{3}[1-9]-(([0][13578]-(0[1-9]|1[012]|2\d|3[01]))|([0][469]-(0[1-9]|1[012]|2\d|30))|(02-(0[1-9]|1[012]|2[0-8]))|(11-(0[1-9]|1[012]|2\d|30))|(12-(0[1-9]|1[012]|2\d|3[01])))"
var regexAllButFeb = new Regex(
    @"
        # DateTime.MinValue => '0001-01-01'
        \d{3}[1-9]
        - 
        (
            # JAN / MAR / MAY / JUL/ AUG
            ([0][13578]-(0[1-9] | 1[012] | 2\d | 3[01]))
            | 
            # APR / JUN / SEP / NOV
            ([0][469]-(0[1-9] | 1[012] | 2\d | 30))
            |
            # FEB
            (02-(0[1-9] | 1[012] | 2[0-8]))
        #   or replace with [0-9] - ^^^^^
            |
            # NOV
            (11-(0[1-9] | 1[012] | 2\d | 30))
            |
            # DEC
            (12-(0[1-9] | 1[012] | 2\d | 3[01]))
        )
    ",
    RegexOptions.Compiled
    | RegexOptions.IgnorePatternWhitespace
);

, (), .;)

+2

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


All Articles