I am creating a DSL with ANTLR 4, and I wonder if it is possible to convert several date format (string) to date with the same function without passing the format for example if my DSL is like that
date1 = "2020-05-08"
date2 = "2020/05/08"
date3 = "20200508"
...
and in my java code I convert the string directly to date without knowing the format for example
Date date1 = convertToDate(date1);
Date date2 = convertToDate(date2);
Date date1 = convertToDate(date3);
instead of writing
Date date1 = convertToDate(date1,"yyyy-mm-dd");
Date date2 = convertToDate(date2,"yyyy/mm/dd");
Date date1 = convertToDate(date3,"yyyymmdd");
Since Java 8, which introduced the new Date and Time API, you are no longer advised to use Date
, Calendar
, SimpleDateFormat
and so on. Those are now legacy types.
Also, if you intend to parse the month, you are supposed to use MM
instead of mm
(which indicates minutes).
With the new Date and Time API, you could use DateTimeFormatter
with optional patterns using [
and ]
. Then you can parse the string dates to LocalDate
instances, as shown below:
DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
.appendPattern("[yyyy-MM-dd]")
.appendPattern("[yyyy/MM/dd]")
.appendPattern("[yyyyMMdd]")
.toFormatter();
LocalDate date1 = LocalDate.parse("2020-05-08", dateFormatter);
LocalDate date2 = LocalDate.parse("2020/05/08", dateFormatter);
LocalDate date3 = LocalDate.parse("20200508", dateFormatter);
System.out.println(date1);
System.out.println(date2);
System.out.println(date3);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments