问题:从前端el-date-picker控件得到的日期,传到java端日期减少一天,存到数据库中又减少一天。
主要原因:主要是前后端数据库时区不统一导致。
解决:将时区统一(或全部使用字符串,这里只介绍时区)。
自定义类CommonConst统一设置时区字符串
public static final String JAVA_TIME_ZONE = "CST";
1、前端将从控件得到的时间对象格式化成字符串传到后台,否则虽然看上去日期是正确的但是传送的时候会少一天。用字符串比较妥当。
var begindate = formatDate(this.datediff[0], 'yyyy-MM-dd') || ''
formatDate函数参考:
2、后端jersey接收时设置时区和格式
@JsonFormat(timezone = CommonConst.JAVA_TIME_ZONE, pattern = "yyyy-MM-dd") @FormParam("enddate") private Date enddate;
也可以使用java转换
DateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd"); dataFormat.setTimeZone(TimeZone.getTimeZone(CommonConst.JAVA_TIME_ZONE)); Date beginDate = null; Date endDate = null; try { beginDate = dataFormat.parse(beginDateStr); endDate = dataFormat.parse(endDateStr); } catch (ParseException e) { e.printStackTrace(); }
3、数据库的时区最好也统一,可以通过修改连接字符串serverTimezone参数实现:
jdbc:mysql://*******:3506/*****?useUnicode=true&characterEncoding=utf-8&serverTimezone=CST&useSSL=true