封面

spring boot做前后分离时间格式化

最近在用spring boot 做数据接口时难免遇到时间这类的问题,接口原则:能服务端处理的别留给客户端。客户端的职责就是把服务端的数据完美的展现出来就好了。所以在返回时间的时候最好先进行一下格式化处理,不要返回时间戳格式。

一、写一个Serializer

然后做一个时间格式化的处理

package info.xiaomo.core.filter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomDateSerializer extends JsonSerializer<Date> {

@Override
public void serialize(Date value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonGenerator.writeString(sdf.format(value));
}
}

二、 使用

在需要转换的时间的Model中加上这个类,仔细观察下面代码中类型为Date的属性

package info.xiaomo.core.model.base;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import info.xiaomo.core.filter.CustomDateSerializer;

import javax.persistence.*;
import java.util.Date;

/**
* 把今天最好的表现当作明天最新的起点..~
* いま 最高の表現 として 明日最新の始発..~
* Today the best performance as tomorrow newest starter!
* Created by IntelliJ IDEA.
*
* @author: xiaomo
* @github: https://github.com/syoubaku
* @email: hupengbest@163.com
* @QQ_NO: 83387856
* @Date: 2016/4/1 20:37
* @Description: model基类
* @Copyright(©) 2015 by xiaomo.
**/

@MappedSuperclass
public abstract class BaseModel {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Id")
private long id;

@Version
@Column(name = "Version")
private long version;

@JsonSerialize(using = CustomDateSerializer.class)
@Column(name = "CreateTime")
private Date createTime;

@JsonSerialize(using = CustomDateSerializer.class)
@Column(name = "UpdateTime")
private Date updateTime;

public Date getUpdateTime() {
return updateTime;
}

public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public long getVersion() {
return version;
}

public void setVersion(long version) {
this.version = version;
}

public Date getCreateTime() {
return createTime;
}

public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
文章目录
  1. 1. 一、写一个Serializer
  2. 2. 二、 使用
twitter分享
Fork me on GitHub