package cn.quantgroup.customer.config.http.mvc.converter;

import org.springframework.core.convert.ConversionFailedException;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;


public class LocalDateConverter implements Converter<String, LocalDate> {
    private final DateTimeFormatter formatter;

    public LocalDateConverter(String dateFormat) {
        this.formatter = DateTimeFormatter.ofPattern(dateFormat);
    }

    @Override
    public LocalDate convert(String source) {
        if (source == null || source.isEmpty()) {
            return null;
        }
        LocalDate obj;
        try {
            obj = LocalDate.parse(source, formatter);
        } catch (ConversionFailedException e) {
            throw new IllegalArgumentException("date format error!");
        }
        return obj;
    }
}
