Modification of date format in FastJson's JSON string

Use toJSONStringWithDateFormat() method

/**
    * 输出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);

   }

Entity class annotation method

Fastjson can freely set the date format on the entity class
@JSONField(format = "yyyy year M, month, d day")
can be set in many kinds, for details, see com.alibaba.fastjson.parser.deserializer.Jdk8DateCodec private constant


/**
 * 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.......
 }
}

Supported formats (not complete)

“yyyy-MM-dd HH:mm:ss”
“yyyy/MM/dd HH:mm:ss”
“yyyy年M月d日 HH:mm:ss”
“yyyy年M月d日 H时m分s秒”
“yyyy년M월d일 HH:mm:ss”
“MM/dd/yyyy HH:mm:ss”
“dd/MM/yyyy HH:mm:ss”
“dd.MM.yyyy HH:mm:ss”
“dd-MM-yyyy HH:mm:ss”
“yyyyMMdd”
“yyyy/MM/dd”
“yyyy年M月d日”
“yyyy년M월d일”
“MM/dd/yyyy”
“dd/MM/yyyy”
“dd.MM.yyyy”
“dd-MM-yyyy”
“yyyy-MM-dd HH:mm:ss”
“yyyy-MM-dd’T’HH:mm:ss”;

Guess you like

Origin blog.csdn.net/qq_41489540/article/details/109093090