Set Current TimeZone to @JsonFormat timezone value

橙三吉。 提交于 2019-12-05 06:52:26

问题


@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy", timezone = "Asia/Kolkata")
private Date activationDate;

Hi Guys,

From the above java code, i want to set timezone value as Current System timezone using below TimeZone.getDefault().getID() - it returns value as "Asia/Kolkata"

But if i set this code to json format

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

I am getting error like "The value for annotation attribute JsonFormat.timezone must be a constant expression"

Pls help me to solve this issue.

Thanks in advance, Vishnu


回答1:


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.




回答2:


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);



回答3:


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 )


来源:https://stackoverflow.com/questions/46011703/set-current-timezone-to-jsonformat-timezone-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!