Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Current TimeZone to @JsonFormat timezone value

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

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

like image 780
Vishnu Moorthy Kanagaraj Avatar asked Sep 02 '17 07:09

Vishnu Moorthy Kanagaraj


2 Answers

You can use JsonFormat.DEFAULT_TIMEZONE, after properly configuring the ObjectMapper:

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

From the docs:

Value that indicates that default TimeZone (from deserialization or serialization context) should be used: annotation does not define value to use.

NOTE: default here does NOT mean JVM defaults but Jackson databindings default, usually UTC, but may be changed on ObjectMapper.

In order to configure the ObjectMapper:

@Configuration
public class MyApp {

    @Autowired
    public void configureJackson(ObjectMapper objectMapper) {
        objectMapper.setTimeZone(TimeZone.getDefault());
    }
}

To set the default TimeZone on your application use this JVM property:

-Duser.timezone=Asia/Kolkata
like image 112
xonya Avatar answered Sep 16 '22 14:09

xonya


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);
like image 28
Raju Sharma Avatar answered Sep 18 '22 14:09

Raju Sharma