java时间戳转Date类型精确到毫秒或微秒存储到mysql

package com.lezu.springboot.test.lian;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.Date;

/**
 * @author LianJiaYu
 * @date 2022/8/18 14:09
 */
public class LianTest3 {

    public static void main(String[] args) {
        /**
         * time字段存储到毫秒需要把数据库中的datetime类型设置被datetime(3)
         * 如果是存入微秒则需要设置为datetime(6)
         */
        String text = "{\n" +
                "    \"time\":\"1661308918662\",\n" +
                "    \"name\":\"支持XML转换Json,Json转XML\"\n" +
                "}";
        Student student = JSONObject.parseObject(text, Student.class);
        System.out.println(student.toString());
        //student{time=Wed Aug 24 10:41:58 CST 2022, name='支持XML转换Json,Json转XML'}

        /**
         * 使用hutool的json转不了date
         */
        System.out.println(JSONUtil.toBean(text, Student.class));
        //Exception in thread "main" cn.hutool.core.date.DateException: No format fit for date String [1661308918662] !
    }


    class Student {
        private Date time;
        private String name;

        public Date getTime() {
            return time;
        }

        public void setTime(Date time) {
            this.time = time;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "student{" +
                    "time=" + time +
                    ", name='" + name + '\'' +
                    '}';
        }


    }

}

TIMESTAMP(3)与 DATETIME(3)意思是保留3为毫秒数

TIMESTAMP(6)与 DATETIME(6)意思是保留6为毫秒数

posted @ 2022-08-24 15:53  难忘是想起  阅读(0)  评论(0)    收藏  举报  来源