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

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

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    private final DateTimeFormatter formatter;

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

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