Note that there are some explanatory texts on larger screens.

plurals
  1. POFastest way to tell if a string is a valid date
    primarykey
    data
    text
    <p>I am supporting a common library at work that performs many checks of a given string to see if it is a valid date. The Java API, commons-lang library, and JodaTime all have methods which can parse a string and turn it in to a date to let you know if it is actually a valid date or not, but I was hoping that there would be a way of doing the validation without actually creating a date object (or DateTime as is the case with the JodaTime library). For example here is a simple piece of example code:</p> <pre><code>public boolean isValidDate(String dateString) { SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); try { df.parse(dateString); return true; } catch (ParseException e) { return false; } } </code></pre> <p>This just seems wasteful to me, we are throwing away the resulting object. From my benchmarks about 5% of our time in this common library is spent validating dates. I'm hoping I'm just missing an obvious API. Any suggestions would be great!</p> <p><strong>UPDATE</strong></p> <p>Assume that we can always use the same date format at all times (likely yyyyMMdd). I did think about using a regex as well, but then it would need to be aware of the number of days in each month, leap years, etc...</p> <hr> <p><strong>Results</strong></p> <p>Parsed a date 10 million times</p> <pre><code>Using Java's SimpleDateFormat: ~32 seconds Using commons-lang DateUtils.parseDate: ~32 seconds Using JodaTime's DateTimeFormatter: ~3.5 seconds Using the pure code/math solution by Slanec: ~0.8 seconds Using precomputed results by Slanec and dfb (minus filling cache): ~0.2 seconds </code></pre> <p>There were some very creative answers, I appreciate it! I guess now I just need to decide how much flexibility I need what I want the code to look like. I'm going to say that dfb's answer is correct because it was purely the fastest which was my original questions. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload