springboot返回时间戳问题
作者:海光之蓝
在SpringBoot中配置时间格式,可以通过配置类或配置文件实现,若需处理日期,可直接在配置文件中设置,存储时间戳毫秒值时,建立数据库字段精度为3,确保时间精确,这些个人经验供参考
springboot返回时间戳
1.springboot加上如下配置类
package com.kaka.mysql.config; 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; /** * @author kaka */ @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; } } } }
2.如果只有date
则可以在配置文件中配置
spring: jackson: serialization: write-dates-as-timestamps: true
3.数据库中如何保存时间戳的毫秒值?
在建数据库字段时,将其精度设置为3即可
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。