sisyphsu / dateparser

dateparser is a smart and high-performance date parser library, it supports hundreds of different formats, nearly all format that we may used. And this is also a showcase for "retree" algorithm.
MIT License
95 stars 24 forks source link

Weird bug - Custom date parser for parsing dates with zero prefixes #33

Open SatheeshJM opened 1 year ago

SatheeshJM commented 1 year ago

For a specific usecase, I needed to parse a date of format yyyy-mm-dd where each component might be prefixed by a zero

I am trying to write a custom parser which is able to parse this

for eg

02022-012-009 should be parsed as 2022-12-09

This is my code


import com.github.sisyphsu.dateparser.DateParser;

public class DateUtilsApplication  {

    public static void main(String[] args) {
        DateParser dateParser = DateParser.newBuilder()
                .addRule("0?(?<year>\\d{4})\\W{1}0?(?<month>\\d{1,2})\\W{1}0?(?<day>\\d{1,2})")
                .build();;

        //example 1  (no zeros)
        System.out.println(dateParser.parseDateTime("2022-12-09").toLocalDate());
        //prints "2022-12-09"

        //example 2 (year, month and date have zero prefix)
        System.out.println(dateParser.parseDateTime("02022-012-009").toLocalDate());
        //prints "2022-12-09"

        //example 3 (month and date have zero prefix)
        System.out.println(dateParser.parseDateTime("2022-012-009").toLocalDate());
        //prints "2022-12-09"

        //example 4 (date has zero prefix)
        System.out.println(dateParser.parseDateTime("2022-12-009").toLocalDate());
        //expected  "2022-12-09", but errors out

    }

}

All examples use the same dateparser but the fourth errors out. very weird because I have given 0? for all 3 components.

What is the problem here?