現(xiàn)在很多人設(shè)計(jì)時(shí)存儲(chǔ)日期都會(huì)用Long類型存儲(chǔ)巧骚,但顯示在前臺(tái)時(shí)撬陵,需要返回日期字符串。
有些人會(huì)讓前端幫忙處理网缝,有些人會(huì)后端處理。
現(xiàn)在只說后端處理的情況蟋定,不需要每次都轉(zhuǎn)換粉臊,通過注解實(shí)現(xiàn)快速轉(zhuǎn)換。
1.實(shí)現(xiàn)轉(zhuǎn)換
public class JSONDateSerial extends JsonSerializer<Long> {
public JSONDateSerial() {
}
public void serialize(Long aLong, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
jsonGenerator.writeString(df.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(aLong), ZoneId.of("Asia/Shanghai"))));
}
}
2.在VO的對(duì)象上驶兜,增加以下注解
/**
* 結(jié)束時(shí)間
*/
@JsonSerialize(using= JSONDateSerial.class)
private Long endDate;
這樣扼仲,返回給前端時(shí)远寸,系統(tǒng)會(huì)自動(dòng)序列化long型為字符串
我的博客即將同步至 OSCHINA 社區(qū),這是我的 OSCHINA ID:愛余星痕屠凶,邀請(qǐng)大家一同入駐:https://www.oschina.net/sharing-plan/apply