React+Antd在使用form表单提交DatePicker日期框的时候会出现少八小时的情况

发布时间 2023-04-11 18:33:47作者: 辣子鸡好吃

在使用antd做form表单提交的时候,突然发现了一个很有意思的bug.就是在使用datepicker组件日期框的时候会出现提交后少一天的问题

我在网上搜索了许多解决办法,也是困扰了我一天的时间,下面代码.

     let formData = JSON.parse(JSON.stringify(form.getFieldsValue()));

        // console.log(formData);
        // console.log(formData.Date1);
        // console.log(moment(formData.Date1));
// console.log(new Date(formData.Date1)); //debugger; formData.Date1= new Date(formData.quotationDate).format("yyyy-MM-dd hh:mm:ss"); formData.Date2 = new Date(formData.quotationInfoDate).format("yyyy-MM-dd hh:mm:ss");

  在log输出的时候,上面三种方法均不行,new Date的方法虽然可以,但是再提交之后就不行了,提交的数据也会自动减少八个小时,最终找到解决办法,在后面加上format,重新渲染格式

  最后在下面加上这个,在提交的时候就不会出现日期减少的问题了

Date.prototype.format = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1,         //月份
        "d+": this.getDate(),          //日
        "h+": this.getHours(),          //小时
        "m+": this.getMinutes(),         //分
        "s+": this.getSeconds(),         //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()       //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};

  在做数据回显的时候,我用的是form.setfiledsvalue(moment(date)),这种方式会导致日期框里面内容错乱

  通过查看官网,发现Antd的DatePicker是基于dayjs的,所以回显数据的时候把moment改为dayjs就可以了