Reputation: 603
I have a simple app with rest сontroller.The app runs in Docker.
@RestController
@Slf4j
public class TimeTestController {
@PostMapping("/time-test")
public @ResponseBody TimeTest timeTest (@RequestBody TimeTest timeTest) {
log.info("request {}", timeTest);
TimeTest time = new TimeTest();
time.setDate(timeTest.getDate());
return time;
}
}
And simple class like this
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TimeTest {
private String id;
private Date date;
}
I pass the date with the time zone to the controller 2020-12-07T19:54:25.860+0100
. However, in the method, the date is printed with timeZone UTC 2020-12-07T18:54:25.860+0000
. And it also returns with timeZone UTC, but I need to return with the same zone as it came. How can I fix this?
Upvotes: 0
Views: 846
Reputation: 2685
Java's Date
a) doesn't support timezone & b) shouldn't be used if you are on Java 8+. I'd suggest using OffsetDateTime
here instead.
Assuming you are using Jackson w/ Spring Boot, in addition to the web
starter make sure to include jackson-datatype-jsr310
as a dependency. When Boot detects it on the classpath, it will automatically configure Jackson's JavaTimeModule
, which supports the new Java8 Date/Time APIs.
Good luck!
Upvotes: 3
Reputation: 79085
It seems your JVM's time zone is UTC. The problem with implementations based on java.util.Date
is that in most cases, they display the date-time in the JVM's time zone. I recommend you use the modern date-time API. Since your date-time string, 2020-12-07T19:54:25.860+0100
has zone offset information, the most appropriate class to use is OffsetDateTime
.
@RestController
@Slf4j
public class TimeTestController {
@PostMapping("/time-test")
public @ResponseBody TimeTest timeTest (@RequestBody TimeTest timeTest) {
log.info("request {}", timeTest);
TimeTest time = new TimeTest();
time.setOdt(timeTest.getDate());// Change timeTest.getDate() to return OffsetDateTime
return time;
}
}
and then in the class, TimeTest
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TimeTest {
private String id;
private OffsetDateTime odt;
}
Learn more about the modern date-time API at Trail: Date Time.
Upvotes: 2