情况一:数据库的日期比页面的日期少一天

页面效果:

 数据库:

 原因分析:使用UTC/GMT会有8小时的时差(中国快全球标准8小时,比如:全球标准当前是上午1点,中国时间则为上午9点),

UTC:Universal Coordinated Time

GMT:格林威治标准时间(Greenwich Mean Time)

我们可以认为格林威治时间就是世界协调时间(GMT=UTC),

UTC + 8小时 = 北京时间

解决办法:可设置为北京时间东八区GMT%2B8 或者上海时间Asia/Shanghai。

原来的时区是这样的:

spring.datasource.url=jdbc:mysql://localhost:63306/mtyh\
  ?characterEncoding=utf8\
  &useoldAliasMetadataBehavior=true\
  &serverTimezone=GMT\
  &useSSL=false

现在改成:

spring.datasource.url=jdbc:mysql://localhost:63306/mtyh\
  ?characterEncoding=utf8\
  &useoldAliasMetadataBehavior=true\
  &serverTimezone=GMT%2B8\
  &useSSL=false

或者

spring.datasource.url=jdbc:mysql://localhost:63306/mtyh\
  ?characterEncoding=utf8\
  &useoldAliasMetadataBehavior=true\
  &serverTimezone=Asia/Shanghai\
  &useSSL=false

情况二、点击编辑按钮,发现日期少一天

效果如下:

后台返回日期格式:

前端列表页面接收:

 

原因分析:列表页面中日期没有少一天,是因为对日期进行格式化导致的。而编辑页面没有进行格式化。

<el-table-column label="灌溉日期" align="center">
        <template slot-scope="scope">{{ scope.row.irrigationDate | formatDate }}</template>
      </el-table-column>

formatDate方法:

    filters: {
      formatDate(time) {
        debugger
        if (time == null || time == "") {
          return "";
        }
        let date = new Date(time);
        return formatDateNew(date, "yyyy-MM-dd");
      },
    },

formatDateNew方法:

export function formatDateNew(date, fmt) {
  debugger
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

后台返回前端,日期少8个小时原因分析:

SpringBoot中对于@RestController或者@Controller+@ResponseBody注解的接口方法的返回值默认是Json格式,所以对于data类型的数据,在返回浏览器段被SpringBoot默认的JackJson框架转换,而JackSon框架默认的时区是GMT,相对于中国少了8个小时。
解决方法:

(1)、设置全局时间字段格式化

在yml配置中或者xml配置中设置:

spring:
  jackson:
    # 格式化全局时间字段 年-月-天 时:分:秒
    date-format: yyyy-MM-dd HH:mm:ss
    # 指定时间区域类型 东8区时区 既北京时间
    time-zone: GMT+8

(2)、第二种方法,在POJO类中添加注解

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date startTime;

(3)、后台返回字符串类型的日期。

List<Map> mapList = plantGrowPestMapper.getPlantGrowPestList(map);
        mapList.forEach(map1 -> {
            if (map1.containsKey("pestDate")) {
                map1.put("pestDate", DateUtil.dateFormat((Date) map1.get("pestDate")));
            }
        });

 

posted on 2021-08-05 19:28  周文豪  阅读(377)  评论(0编辑  收藏  举报