dateparser
dateparser copied to clipboard
Weird bug - Custom date parser for parsing dates with zero prefixes
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?