【Tools】SpringBoot工程中,对于时间属性从后端返回到前端的格式问题

Catalog

  • 时间属性格式问题
    • 一、需求
    • 二、怎么使用

时间属性格式问题

一、需求

对于表中时间字段,后端创建对应的实体类的时间属性需要设定格式(默认的格式不方便阅读),再返回给前端。

二、怎么使用

  1. 导入jackson相关的坐标,SpringBoot工程中,一般默认在web的starter包里面。

        
        
            com.fasterxml.jackson.core
            jackson-annotations
            2.12.3 
        
        
        
        
            com.fasterxml.jackson.core
            jackson-core
            2.12.3
        
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.12.3
        
    

    【Tools】SpringBoot工程中,对于时间属性从后端返回到前端的格式问题_第1张图片

  2. 使用@JsonFormat注解,在实体类的时间属性上面添加(“设置日期的显示格式和时区”),y\m\d\h\m\s分别代别年月日时分秒

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
        private Date createTime;
    
  3. 或者在SpringBoot的配置文件中配置

    spring:
      jackson:
        date-format: yyyy-mm-dd HH:mm:ss
        time-zone: GMT+8
    

tips:时间戳格式转换

     /**
         * 时间格式刷
         * @return
         */
        public static String dateBrush(){
            //获取格式刷
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            long currentTime = System.currentTimeMillis();

            //将时间戳转换为时间类型
            Date date = new Date(currentTime);

            //调用格式刷
            String dataStr = simpleDateFormat.format(date);

            return dataStr;
        }

你可能感兴趣的:(Tools,spring,boot,前端,后端)