Reputation: 433
I want to convert my string into valid date format even months and days are optional
For Example, I have the following string like below
String date1 = "20-12-2021"
String date2 = "12-2021" i.e without day
String date3 = "2021" i.e without day & month
String date4 = "21" i.e without day, month & just last two digits of the year
I want to convert all the above strings format into the valid date with 'yyyy-mm-dd' format as below,
For date1, Date should be "2021-12-20"
For date2, Date should be "2021-12-01"
For date3, Date should be "2021-01-01"
For date4, Date should be "2021-01-01"
Could you please help me with this? Any info will be really helpful. I can't define single string formatted for parser since the string format is unpredictable in my scenario.
Upvotes: 3
Views: 561
Reputation: 9881
A whacky yet working solution in your special case would be the following:
public class DateParser {
private static String defaultDate = "01-01-2000";
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
public static LocalDate parseDate(String date) {
String fullDate = defaultDate.substring(0, defaultDate.length() - date.length()) + date;
return LocalDate.parse(fullDate, formatter);
}
}
Basically, use a default full date, e.g. 01-01-2000
, and then combine it with the input date. Then, use the formatter dd-MM-yyyy
to parse the date. One of the advantages is that it reuses the same formatter, hence is very efficient. However, you may need to add some checks and exception handling.
To test it:
public static void main(String[] args) {
List.of(
"20-12-2021",
"12-2021",
"2021",
"21"
).forEach(date -> System.out.println(parseDate(date)));
}
Output:
2021-12-20
2021-12-01
2021-01-01
2021-01-01
(I must admit @YCF_L solution is more elegant though)
Upvotes: 2
Reputation: 60026
You can use DateTimeFormatterBuilder
with multiple patterns and default values of missing parts (month and day):
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("[dd-MM-uuuu]")
.appendPattern("[MM-uuuu]")
.appendPattern("[uuuu]")
.appendPattern("[uu]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();
Outputs
2021-12-20
2021-12-01
2021-01-01
2021-01-01
Upvotes: 7