【Java】全域性日期處理,包含LocalDate, LocalDateTime, Date

清清飞扬發表於2024-07-08

共包含3個檔案:

1. DateFormatConfig.java

package com.yykj.lckj.common.config;

import com.alibaba.fastjson2.util.DateUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@JsonComponent
public class DateFormatConfig {

    private final static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private final static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

    /**
     * LocalDateTime: 字串反序列化
     */
    public static class DateJsonDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            return DateUtils.parseLocalDateTime(jsonParser.getText());
        }
    }

    /**
     * LocalDateTime序列化
     */
    public static class DateJsonSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(localDateTime.format(dateTimeFormatter));
        }
    }

    /**
     * LocalTime序列化
     */
    public static class TimeJsonSerializer extends JsonSerializer<LocalTime> {
        @Override
        public void serialize(LocalTime localTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(localTime.format(timeFormatter));
        }
    }
}

  

2. WebMvcConfiguration.java

package com.yykj.lckj.common.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Nonnull;
import java.text.ParseException;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @Override
    public void addFormatters(@Nonnull FormatterRegistry registry) {
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setTimeFormatter(TIME_FORMATTER);
        registrar.setDateFormatter(DATE_FORMATTER);
        registrar.setDateTimeFormatter(DATETIME_FORMATTER);
        registrar.registerFormatters(registry);
        registry.addFormatter(new CompositeFormatter());
    }

    /**
     * java.util.Date日期格式化.
     */
    private static class CompositeFormatter implements Formatter<Date> {
        private final List<Formatter<Date>> formatters = Arrays.asList(
            new DateFormatter("yyyy-MM-dd HH:mm:ss"),
            new DateFormatter("yyyy-MM-dd"),
            new DateFormatter("HH:mm:ss")
        );

        @Override
        public @Nonnull Date parse(@Nonnull String text, @Nonnull Locale locale) throws ParseException {
            for (Formatter<Date> formatter : formatters) {
                try {
                    return formatter.parse(text, locale);
                } catch (ParseException ignored) {
                }
            }
            throw new ParseException("Unable to parse date: " + text, 0);
        }

        @Override
        public @Nonnull String print(@Nonnull Date date, @Nonnull Locale locale) {
            return formatters.get(0).print(date, locale);
        }
    }
}

  

3. GlobalControllerAdvice.java

package com.yykj.lckj.common.config;

import com.alibaba.fastjson2.util.DateUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.time.LocalDateTime;

@ControllerAdvice
public class GlobalControllerAdvice {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseLocalDateTime(text));
            }
        });
    }
}

  

相關文章