springboot返回時間戳問題
更新時間:2024年09月25日 09:31:58 作者:海光之藍(lán)
在SpringBoot中配置時間格式,可以通過配置類或配置文件實現(xiàn),若需處理日期,可直接在配置文件中設(shè)置,存儲時間戳毫秒值時,建立數(shù)據(jù)庫字段精度為3,確保時間精確,這些個人經(jīng)驗供參考
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;
}
/**
* 序列化實現(xiàn)
*/
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);
}
}
}
/**
* 反序列化實現(xiàn)
*/
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.數(shù)據(jù)庫中如何保存時間戳的毫秒值?
在建數(shù)據(jù)庫字段時,將其精度設(shè)置為3即可

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決MyBatis-Plus使用動態(tài)表名selectPage不生效的問題
這篇文章主要介紹了如惡化解決MyBatis-Plus使用動態(tài)表名selectPage不生效的問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11
使用SpringBoot + Redis + Vue實現(xiàn)動態(tài)路由加載頁面的示例代
在現(xiàn)代 Web 應(yīng)用開發(fā)中,動態(tài)路由加載能夠顯著提升應(yīng)用的靈活性和安全性,本文將深入探討如何利用 Spring Boot、Redis、Element UI 和 Vue 技術(shù)棧實現(xiàn)動態(tài)路由加載,并通過 Redis 生成和驗證有效鏈接以實現(xiàn)頁面訪問控制,需要的朋友可以參考下2024-09-09
Java的Jackson庫的使用及其樹模型的入門學(xué)習(xí)教程
這篇文章主要介紹了Java的Jackson庫的使用及其樹模型入門學(xué)習(xí)教程,Jackson庫通常被用來作Java對象和JSON的互相轉(zhuǎn)換,需要的朋友可以參考下2016-01-01
關(guān)于SpringBoot自定義條件注解與自動配置
這篇文章主要介紹了關(guān)于SpringBoot自定義條件注解與自動配置,Spring Boot的核心功能就是為整合第三方框架提供自動配置,而本文則帶著大家實現(xiàn)了自己的自動配置和Starter,需要的朋友可以參考下2023-07-07

