SpringBoot&fastjson中用@JSONFormat格式化日期格式/指定日期属性的格式

问题背景

json默认格式化时间都是时间戳,这样看起来很不明显,前端可能还需要再度格式化;之前一直都有用,忘记整理出来了,这个纯属整理

2020年7月12日 修订:更新为@JSONFormat

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8")

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

解决方案

新版@JSONFormat
/**
 * 有效日期:开始时间
 */
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date certValidateStart;

/**
 * 有效日期:结束时间
 */
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date certValidateEnd;

在这里插入图片描述

旧版@JSONField

第一种是最推荐的,用注解来实现,也很好理解。
SpringBoot&fastjson中用@JSONFormat格式化日期格式/指定日期属性的格式_第1张图片

    /**
     * 停止注册时间
     */
    @JSONField(format="yyyy-MM-dd HH:mm:ss")
    private Date regCloseTime;

第二种是JSON.toJSONString的时候用的,一般保存str到数据库或者debug会方便一些

JSONObject.DEFFAULT_DATE_FORMAT="yyyy-MM-dd";//设置日期格式

String jsonStr=JSONObject.toJSONString(object, SerializerFeature.WriteDateUseDateFormat);

第三种

String newsJSON = JSON.toJSONStringWithDataFormat( list,"yyyy-MM-dd HH:mm:ss" );

你可能感兴趣的:(Spring,SpringBoot2启示录)