bug记录

Date类型接收CST时间格式

2020-04-11  本文已影响0人  修行者12138

springmvc接收Date类型入参时,如果参数是CST格式的字符串,如
localhost:8004/test?date=Wed Apr 24 16:07:58 CST 2019,
会出现接收到的日期与参数不一致的问题

image.png

观察接口实际接收到的日期,发现比入参多了14个小时,而美国中部(西六区)与北京(东八区)正好差了14个时区,因此猜测springmvc把入参当作美国中部时间,然后转化为北京时间,因此多了14个小时。

因此,应该先用西六区把入参解析为字符串,再用东八区把字符串转化回时间,代码如下

    public Date changeTimeZone (Date date) throws Exception{
        DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'CST' yyyy", Locale.US);
        df.setTimeZone(TimeZone.getTimeZone("GMT-6"));
        String cstStr = df.format(date);
        df.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        date = df.parse(cstStr);
        System.out.println(date);
        return date;
    }

GMT UTC CST几种时间格式的介绍可以看这篇文章
https://www.jianshu.com/p/7acb500ec572

上一篇 下一篇

猜你喜欢

热点阅读