下载搜学网app
查学校 查学区 查辅导 查饭桌 查询中考数据
logo 点击咨询

SpringBoot中json处理日期类型的问题


SpringBoot中涉及到时间日期型的处理问题,有下述容易出错的地方:

  1. 数据库时区设置:

spring.datasource.url=jdbc:mysql://localhost:3306/${table.schema}?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8     

注意上面的serverTimezone,比如中国是东八区,应设置为=GMT%2B8,依次类推。


2.默认的json格式化date类型的错误:JSON.stringify()函数默认的将Date类型格式化为UTC时间,结果就跟中国的时间差了8小时,这个处理方法网上有很多相互抄的帖子,基本思路说的都对,就是重载Es5的Date.prototype.toJSON方法,但是很明显都是相互抄的,都把“重载”copy成“重新”了。鄙视!!!

正确的做法应该是这样:

a)重新定义dateFormat函数,如下:

function dateFormat(date, fmt) {
    if (null == date || undefined == date) return '';
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var 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;
}

b)在调用JSON.stringify()函数之前添加下列语句:

Date.prototype.toJSON = function () { return dateFormat(this,'yyyy-MM-dd')};

供参考。



评论