So am parsing json and sometimes the string I receive which contains the date comes full(dd-mm-yyyy) , and sometimes I only receive yyyy which I dont seem to able to convert to date ,so if anyone can help
解决方案
As per your business requirement, you can default the month and the day-of-month to the required value using DateTimeFormatterBuilder#parseDefaulting e.g. in the following code, I have defaulted the month and the day-of-month to that of today:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
class Main {
public static void main(String[] args) {
// Test
System.out.println(parseToDate("10-10-2020"));
System.out.println(parseToDate("2020"));
}
static LocalDate parseToDate(String str) {
LocalDate today = LocalDate.now();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("[dd-MM-uuuu][uuuu]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, today.getMonthValue())
.parseDefaulting(ChronoField.DAY_OF_MONTH, today.getDayOfMonth())
.toFormatter(Locale.ENGLISH);
return LocalDate.parse(str, formatter);
}
}
Output:
2020-10-10
2020-12-12
Note: The pattern, [dd-MM-uuuu][uuuu] has two optional patterns, dd-MM-uuuu and uuuu.