Đây là solution
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.List;
import java.util.stream.Collectors;
public class Demo {
@Test
void name() throws IOException{
List<String> dates = getDateFromCsv(); //đọc file csv
DateTimeFormatter formatter = getDateFormatter(); //tạo định dạng date
List<LocalDate> dateList = dates.stream() //chuyển string -> date
.map(date -> parseDate(formatter, date))
.collect(Collectors.toList());
System.out.println(dateList);
}
private DateTimeFormatter getDateFormatter() {
return new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern("d-M-yyyy"))
.appendOptional(DateTimeFormatter.ofPattern("d.M.yyyy"))
.appendOptional(DateTimeFormatter.ofPattern("dd/M/yyyy"))
.toFormatter();
}
private List<String> getDateFromCsv() throws IOException {
Path path = Path.of("src/test/resources/date.csv");
List<String> strings = Files.readAllLines(path);
System.out.println(strings);
return strings;
}
private LocalDate parseDate(DateTimeFormatter formatter, String text) {
return LocalDate.parse(text, formatter);
}
}
Với data mẫu ở đề bài, thì khi run code, error sẽ throw ở dòng số 4, vì không có định dạng giống như định nghĩa.
[2-1-2019, 10.07.2021, 15/10/2020, -1-2-9999] java.time.format.DateTimeParseException: Text '-1-2-9999' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): -1