none
regex for string date RRS feed

Answers

  • If you only want to check the pattern roughly, you can use this expression for example: 

    ^\d{4}\-(0[1-9]|1[12])\-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3])(\:[0-5]\d){2}\.\d{3}$

    However, this does not cover all cases with invalid dates. For example, 2017-02-31T12:00:00:00.000 would match, but is not a valid date.

    It would be simpler and more reliable to use DateTime.TryParseExact.

    • Proposed as answer by Wild.Bill.Work Tuesday, November 14, 2017 7:52 PM
    • Marked as answer by arkiboys Sunday, November 26, 2017 3:24 PM
    Tuesday, November 14, 2017 7:32 PM

All replies

  • If you only want to check the pattern roughly, you can use this expression for example: 

    ^\d{4}\-(0[1-9]|1[12])\-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3])(\:[0-5]\d){2}\.\d{3}$

    However, this does not cover all cases with invalid dates. For example, 2017-02-31T12:00:00:00.000 would match, but is not a valid date.

    It would be simpler and more reliable to use DateTime.TryParseExact.

    • Proposed as answer by Wild.Bill.Work Tuesday, November 14, 2017 7:52 PM
    • Marked as answer by arkiboys Sunday, November 26, 2017 3:24 PM
    Tuesday, November 14, 2017 7:32 PM
  • Hello ,

    If you only pay attention to date format and don't care date number limit, try the below code.

          string s1 = "2017-09-19T08:07:32.591";
                string s2 = "2017-09-19T08:07:32.";
    
               string regex= @"^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})$";
    
                Boolean isValild1 = Regex.IsMatch(s1,regex);

    Sincerely,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, November 15, 2017 8:36 AM
    Moderator
  • Hello arikiboys,

    Did you have anything to update?  If you already have got the useful solution from there, you could close the thread by marking the useful reply  as answer, This can be beneficial to other community members reading this thread. Thanks a lot.

    Sincerely,
    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Sunday, November 26, 2017 11:52 AM
    Moderator