目录
- springboot返回时间戳
- 1.springboot加上如下配置类
- 2.如果只有date
- 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 {
android /**
* 序列化LocalDateTime
* @return
*/
@Bean
@Primary
public ObjectMapper serializingObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule =android new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDesejsrializer());
objectMapper.registerModule(javaTimeModule);
编程客栈 return objectMapper;
}
/**
* 序列化实现
*/
public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
throws IOExcepti编程客栈on {
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即可

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
加载中,请稍侯......
精彩评论