How to check if a string is a valid date

后端 未结 15 1527
礼貌的吻别
礼貌的吻别 2020-12-02 08:09

I have a string: \"31-02-2010\" and want to check whether or not it is a valid date. What is the best way to do it?

I need a method which which returns

15条回答
  •  广开言路
    2020-12-02 08:37

    Try regex for all dates:

    /(\d{1,2}[-\/]\d{1,2}[-\/]\d{4})|(\d{4}[-\/]\d{1,2}[-\/]\d{1,2})/.match("31-02-2010")
    

    For only your format with leading zeroes, year last and dashes:

    /(\d{2}-\d{2}-\d{4})/.match("31-02-2010")
    

    the [-/] means either - or /, the forward slash must be escaped. You can test this on http://gskinner.com/RegExr/

    add the following lines, they will all be highlighted if you use the first regex, without the first and last / (they are for use in ruby code).

    2004-02-01
    2004/02/01
    01-02-2004
    1-2-2004
    2004-2-1
    

提交回复
热议问题