What is best ways to validate string date to be valid date according to format?

后端 未结 4 1328
情话喂你
情话喂你 2020-12-21 22:44

Started working with WEB UI recently. And encountered a problem of date string parsing/validation. \"dd-mm-yyyy\" Some approaches I found are:

  1. Matching -

4条回答
  •  旧巷少年郎
    2020-12-21 23:06

    If you have a known list of formats you want to support, you can create instances of the thread-safe org.joda.time.format.DateTimeFormatter, place them into a list, and iterate until one of them can successfully parse the date. Memory consumption for these parsers is negligible, and you can use the resulting date object once you find the matching format.

    This also has the benefit of being far more readable than regex. Beware of using regex for formats that can be ambiguous like mm-dd-yyyy vs. dd-mm-yyyy.

提交回复
热议问题