zoukankan      html  css  js  c++  java
  • 关于页面显示JSON时间戳问题

    JSON时间戳

    后端返回前端JSON数据为时间戳,用封装和重载思想,写一个不返回时间戳工具类,调用这个方法,页面可以显示自己想要的时间样式,这里采用"yyyy-MM-dd HH:mm:ss"。

    引用B站:狂神说

    utils:

    package com.godwin.utils;
    
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    
    import java.text.SimpleDateFormat;
    
    /**
     * 不返回时间戳
     * Created by Godwin on 2020/12/21.
     */
    public class JsonUtils {
    
        public static String getJson(Object object){
            return getJson(object,"yyyy-MM-dd HH:mm:ss");
        }
    
        public static String getJson(Object object,String dataFormat){
            ObjectMapper mapper = new ObjectMapper();
            //1.如何让他不返回时间戳!所以我们要关闭它的时间戳功能
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
            //2.时间格式化问题!自定日期格式对象
            SimpleDateFormat sdf = new SimpleDateFormat(dataFormat);
            //3.让mapper指定时间日期格式为sdf
            mapper.setDateFormat(sdf);
            try {
                return mapper.writeValueAsString(object);
            }catch (JsonProcessingException e){
                e.printStackTrace();
            }
            return null;
        }
    }
    
    

    controller:

    package com.godwin.controller;
    
    import com.godwin.utils.JsonUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.Date;
    
    /**
     * Created by Godwin on 2020/12/21.
     */
    @Controller
    public class JsonController {
    
        @RequestMapping("/test")
        @ResponseBody//将java对象转换为json数据
        public String json(){
            Date date = new Date();
            return JsonUtils.getJson(date);
        }
    }
    
    

    运行项目,并打开网页输出:http://localhost:8080/test

    点击此处直接进入http://localhost:8080/test

    按照上述操作,网页会显示:

    "2020-12-21 09:56:12"

  • 相关阅读:
    KVM克隆CentOS6虚拟机后无法启动
    Python socket网络模块
    LNMP的安装--详细版
    CentOS7 二进制安装MySQL5.6.42
    超越线程池:Java并发并没有你想的那么糟糕
    有哪些实用的计算机相关技能,可以在一天内学会?
    如何写出让hr一看就约你面试的简历
    五个最佳编程字体
    Eclipse 的 Debug 介绍与技巧
    Redis时延问题分析及应对
  • 原文地址:https://www.cnblogs.com/XING-ZHI-JI-DA-XUE/p/14166561.html
Copyright © 2011-2022 走看看