Set Current TimeZone to @JsonFormat timezone value

自古美人都是妖i 提交于 2019-12-03 20:36:46

You can use JsonFormat.DEFAULT_TIMEZONE:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy", timezone = JsonFormat.DEFAULT_TIMEZONE)

From the docs:

Special value of DEFAULT_TIMEZONE can be used to mean "just use the default", where default is specified by the serialization context, which in turn defaults to system defaults (TimeZone.getDefault()) unless explicitly set to another locale.

You cannot assign timezone value a dynamic or a runtime value. It should be constant or a compile time value and enums too accepted.

So you should assign a constant to timezone. like below.

private static final String MY_TIME_ZONE="Asia/Kolkata";
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy", timezone = MY_TIME_ZONE);

You can use enumeration in order to possibly enrich you time zones that you would use. A solution using enumeration is the following enumeration class implementation.

    package <your package goes here>;

    import java.util.TimeZone;


    public enum TimeZoneEnum {

        DEFAULT(TimeZone.getDefault()),
        ASIA_KOLKATA = (TimeZone.getTimeZone("Africa/Abidjan")),
        //other timezones you maybe need
        ...


    private final TimeZone tz;

        private TimeZoneEnum(final TimeZone tz)
        {
            this.tz = tz;
        }

        public final TimeZone getTimeZone()
        {
            return tz;
        }
    }

Then you can utilize you enumeration like below:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy", timezone = TimeZoneEnum.ASIA_KOLKATA )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!