How to check if a string is a valid date

后端 未结 15 1509
礼貌的吻别
礼貌的吻别 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:50

    Here is a simple one liner:

    DateTime.parse date rescue nil
    

    I probably wouldn't recommend doing exactly this in every situation in real life as you force the caller to check for nil, eg. particularly when formatting. If you return a default date|error it may be friendlier.

提交回复
热议问题