Utilice el método toJSONStringWithDateFormat ()
/**
* 输出json同时指定日期格式
*/
@Test
public void ceui() {
HashMap<String, Object> map = new HashMap<>();
map.put("date", new Date());
map.put("name", "张三");
map.put("date2", new Date());
// String s = JSON.toJSONStringWithDateFormat(map, "yyyy-MM-dd HH:mm:ss");
//结果 {"date":"2019-08-30 14:11:39","name":"张三","date2":"2019-08-30 14:11:39"}
// String s = JSON.toJSONStringWithDateFormat(map, "yyyy-MM-dd");
//结果 {"date":"2019-08-30","name":"张三","date2":"2019-08-30"}
String s = JSON.toJSONStringWithDateFormat(map, "yyyy年MM月dd日 HH时mm分ss");
//结果 {"date":"2019年08月30日 14时12分33","name":"张三","date2":"2019年08月30日 14时12分33"}
System.out.println(s);
}
Método de anotación de clase de entidad
Fastjson puede configurar libremente el formato de fecha en la clase de entidad
@JSONField (formato = "yyyy año M mes d día")
se puede configurar de varias maneras, necesita ver com.alibaba.fastjson.parser.deserializer.Jdk8DateCodec constante privada bajo esta clase
/**
* Fastjson能识别很多种日期格式,具体识别哪些格式看
*
* @com.alibaba.fastjson.parser.deserializer.Jdk8DateCodec 这个类
*/
public class DateTimeDemo {
@Test
public void ceui1() {
Model model = new Model();
model.setDate(new Date());
String jsonString = JSON.toJSONString(model);
System.out.println("jsonString = " + jsonString);
// 可以使用@JSONField 切换格式
//jsonString = {"date":"八月 30, 2019 11:02:36 上午"}
//jsonString = {"date":"2019-08-30 11:04:30"}
//jsonString = {"date":"2019"}
}
/**
* 内部类
*/
static class Model {
// @JSONField(format = "MMM dd, yyyy h:mm:ss aa")
// @JSONField(format = "yyyy-MM-dd HH:mm:ss")
@JSONField(format = "yyyy")
private java.util.Date date;
//省略getset.......
}
}
Formatos admitidos (no completos)
“Aaaa-MM-dd HH: mm: ss”
“aaaa / MM / dd HH: mm: ss”
“aaaa 年 M 月 d 日 HH: mm: ss”
“aaaa 年 M 月 d 日 H 时 m 分 s 秒"
" Aaaa 년 M 월 d 일 HH: mm: ss "
" MM / dd / aaaa HH: mm: ss "
" dd / MM / aaaa HH: mm: ss "
" dd.MM.yyyy HH: mm: ss "
“Dd-MM-aaaa HH: mm: ss”
“aaaaMMdd”
“aaaa / MM / dd”
“aaaa 年 M 月 d 日”
“aaaa 년 M 월 d 일”
“MM / dd / aaaa”
“dd / MM / aaaa ”
“ dd.MM.yyyy ”
“ dd-MM-aaaa ”
“ aaaa-MM-dd HH: mm: ss ”
“ aaaa-MM-dd'T'HH: mm: ss ”;