代码改变世界

JsonFormat 日期少了8个小时?

2020-03-17 17:03  tony4geek  阅读(2625)  评论(2编辑  收藏  举报

JsonFormat 后日期少了8个小时什么鬼?

前言

今天测试的时候发现时间对不上,比数据库里的时间少了8个小时?测试小姐姐一顿狂轰乱炸,一点都不温柔。

什么鬼?哪里出了问题?
数据库显示的是下面👇


画面显示如下

我的数据里明明显示的是对的时间,怎么到画面显示你就少了8个小时?

快,还我8个小时。

扯远了,赶紧撸代码,找问题。

数据库里显示的是
2020-03-17 11:40:27

然而到了画面前端显示的是
2020-03-17 03:40:27

分析

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

应该就是上面的代码出了问题,没关系,出问题慢慢解决。

看看源码

@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonFormat {
    String DEFAULT_LOCALE = "##default";
    String DEFAULT_TIMEZONE = "##default";

    String pattern() default "";

    JsonFormat.Shape shape() default JsonFormat.Shape.ANY;

    String locale() default "##default";

    String timezone() default "##default";

    JsonFormat.Feature[] with() default {};

    JsonFormat.Feature[] without() default {};
}

JsonFormat 是一个注解,上面的createTime,我们配置的pattern时间的格式,其他的都是默认的。

少了8个小时?是不是会是时区的问题,接着往下面看,眼前一亮呀。

    //java.util.TimeZone to use for serialization (if needed)
    public String timezone() default DEFAULT_TIMEZONE;

不设置时区的话,会有个默认的时区。

网上找找代码看看时区的数据

 public static void main(String[] args) {
        System.out.println(TimeZone.getDefault().getID());

        String[] ids = TimeZone.getAvailableIDs();
        for (String id : ids) {
            System.out.println(displayTimeZone(TimeZone.getTimeZone(id)));
        }

        System.out.println("\nTotal TimeZone ID " + ids.length);

    }


    private static String displayTimeZone(TimeZone tz) {

        long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
        long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
            - TimeUnit.HOURS.toMinutes(hours);
        // avoid -4:-30 issue
        minutes = Math.abs(minutes);

        String result = "";
        if (hours > 0) {
            result = String.format("(GMT+%d:%02d) %s", hours, minutes, tz.getID());
        } else {
            result = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID());
        }

        return result;

    }

输出结果

Asia/Shanghai
(GMT-12:00) Etc/GMT+12
(GMT-11:00) Etc/GMT+11
(GMT-11:00) Pacific/Midway
(GMT-11:00) Pacific/Niue
(GMT-11:00) Pacific/Pago_Pago
(GMT-11:00) Pacific/Samoa
(GMT-11:00) US/Samoa
(GMT-10:00) America/Adak
(GMT-10:00) America/Atka
(GMT-10:00) Etc/GMT+10
(GMT-10:00) HST
(GMT-10:00) Pacific/Honolulu
(GMT-10:00) Pacific/Johnston
(GMT-10:00) Pacific/Rarotonga
(GMT-10:00) Pacific/Tahiti
(GMT-10:00) SystemV/HST10
(GMT-10:00) US/Aleutian
(GMT-10:00) US/Hawaii
(GMT-9:30) Pacific/Marquesas
省略……
Total TimeZone ID 620

我们再看看

 public TimeZone getTimeZone() {
            TimeZone tz = this._timezone;
            if (tz == null) {
                if (this._timezoneStr == null) {
                    return null;
                }

                tz = TimeZone.getTimeZone(this._timezoneStr);
                this._timezone = tz;
            }

            return tz;
        }

    /**
     * Gets the <code>TimeZone</code> for the given ID.
     *
     * @param ID the ID for a <code>TimeZone</code>, either an abbreviation
     * such as "PST", a full name such as "America/Los_Angeles", or a custom
     * ID such as "GMT-8:00". Note that the support of abbreviations is
     * for JDK 1.1.x compatibility only and full names should be used.
     *
     * @return the specified <code>TimeZone</code>, or the GMT zone if the given ID
     * cannot be understood.
     */

    public static synchronized TimeZone getTimeZone(String ID) {
        return getTimeZone(ID, true);
    }

    private static TimeZone getTimeZone(String ID, boolean fallback) {
        TimeZone tz = ZoneInfo.getTimeZone(ID);
        if (tz == null) {
            tz = parseCustomTimeZone(ID);
            if (tz == null && fallback) {
                tz = new ZoneInfo(GMT_ID, 0);
            }
        }
        return tz;
    }

timezone

1.1 什么是时区?
timezone,即由于世界各国家与地区经度不同,地方时也有所不同,按照经度将全球划分为24个时区。

由于世界各国家与地区经度不同,地方时也有所不同,因此会划分为不同的时区。

时区有相应的英文字母缩写,例如GMT,UTC,CST等,常见的时区。

正确写法

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

千万别忘记加时区timezone = "GMT+8"

真的是开发的bug无处不在,看来开发的时候还得多小心。