springboot返回时间戳问题
更新时间:2024年09月25日 09:31:58 作者:海光之蓝
在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: true3.数据库中如何保存时间戳的毫秒值?
在建数据库字段时,将其精度设置为3即可

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Spring Boot Admin集成与自定义监控告警示例详解
SpringBootAdmin是一个管理和监控SpringBoot应用程序的工具,可通过集成和配置实现应用监控与告警功能,本文给大家介绍Spring Boot Admin集成与自定义监控告警示例详解,感兴趣的朋友跟随小编一起看看吧2024-09-09
JVM---jstack分析Java线程CPU占用,线程死锁的解决
这篇文章主要介绍了JVM---jstack分析Java线程CPU占用,线程死锁的解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-09-09
IDEA插件之Mybatis Log plugin 破解及安装方法
这篇文章主要介绍了IDEA插件之Mybatis Log plugin 破解方法及安装方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-09-09


最新评论