Fastest way to tell if a string is a valid date

前端 未结 8 1162
故里飘歌
故里飘歌 2020-12-13 04:52

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

8条回答
  •  长情又很酷
    2020-12-13 05:30

    If you're really concerned about performance and your date format is really that simple, just pre-compute all the valid strings and hash them in memory. The format you have above only has ~ 8 million valid combinations up to 2050


    EDIT by Slanec - reference implementation

    This implementation depends on your specific dateformat. It could be adapted to any specific dateformat out there (just like my first answer, but a bit better).

    It makes a set of all dates from 1900 to 2050 (stored as Strings - there are 54787 of them) and then compares the given dates with those stored.

    Once the dates set is created, it's fast as hell. A quick microbenchmark showed an improvement by a factor of 10 over my first solution.

    private static Set dates = new HashSet();
    static {
        for (int year = 1900; year < 2050; year++) {
            for (int month = 1; month <= 12; month++) {
                for (int day = 1; day <= daysInMonth(year, month); day++) {
                    StringBuilder date = new StringBuilder();
                    date.append(String.format("%04d", year));
                    date.append(String.format("%02d", month));
                    date.append(String.format("%02d", day));
                    dates.add(date.toString());
                }
            }
        }
    }
    
    public static boolean isValidDate2(String dateString) {
        return dates.contains(dateString);
    }
    

    P.S. It can be modified to use Set or even Trove's TIntHashSet which reduces memory usage a lot (and therefore allows to use a much larger timespan), the performance then drops to a level just below my original solution.

提交回复
热议问题