0
点赞
收藏
分享

微信扫一扫

Java前后端实现Date、LocalDateTime与时间戳转换

肉肉七七 2022-02-22 阅读 72

1、Date与时间戳转换

1、实体类:
实体类中,时间类型字段使用Date 类型修饰。

public class User implements Serializable {
    private static final long serialVersionUID = 621747518161198596L;
    /**
     * 用户id
     */
    private String id;
    /**
     * 用户名称
     */
    private String name;
   
    /**
     * 创建时间
     */
    private Date createTime;
  
    /**
     * 更新时间
     */
    private Date updateTime;
	
}

2、配置转换器:

public class TimeStampToDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String text) {
        Date date = null;

        if (StringUtils.isNotEmpty(text)) {
            date = new Date(Long.parseLong(text));
        }

        return date;
    }
}

3、注册转换器:
通过继承WebMvcConfigurationSupport类,重写addFormatters方法

@Configuration
public class WebMvcRegistrationsConfig extends WebMvcConfigurationSupport {
	...
	/**
     * 添加自定义消息转换器
     */
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        // 添加时间戳转日期类型消息转换器
        registry.addConverter(new TimeStampToDateConverter());
    }
	...
}

2、LocalDateTime与时间戳转换

1、实体类:
实体类中,时间类型字段使用LocalDateTime类型修饰。

public class User implements Serializable {
    private static final long serialVersionUID = 621747518161198596L;
    /**
     * 用户id
     */
    private String id;
    /**
     * 用户名称
     */
    private String name;
   
    /**
     * 创建时间
     */
    private LocalDateTimecreateTime;
  
    /**
     * 更新时间
     */
    private LocalDateTimeupdateTime;
	
}

2、配置转换器:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Configuration
public class LocalDateTimeSerializerConfig {
    /**
     * 序列化LocalDateTime
     *
     * @return
     */
    @Bean
    @Primary
    public ObjectMapper serializingObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

    /**
     * 序列化实现
     */
    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException {
            if (value != null) {
                long timestamp = value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                gen.writeNumber(timestamp);
            }
        }
    }

    /**
     * 反序列化实现
     */
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
                throws IOException {
            long timestamp = p.getValueAsLong();
            if (timestamp > 0) {
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
            } else {
                return null;
            }
        }
    }
}

3、注册转换器:
通过继承WebMvcConfigurationSupport类,重写extendMessageConverters方法

@Configuration
public class WebMvcRegistrationsConfig extends WebMvcConfigurationSupport {
    // 注入ObjectMapper 
	@Resource
    private ObjectMapper serializingObjectMapper;
	...
	/**
     * 添加自定义消息转换器
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(serializingObjectMapper);
        converters.add(0, converter);
    }
	...
}
举报

相关推荐

0 条评论