2
我在我的數據庫上保存日期而沒有時間戳,所以我想標準化我的Spring Boot Rest控制器接收日期的方式,因此服務可以是部署在世界任何地方(AWS EC2等)。春季啓動+傑克遜 - 總是將日期轉換爲UTC
我試圖設置下列屬性,並沒有幫助:
spring.jackson.time-zone=UTC
還有另一種屬性,它始終是true
,所以我沒有設置,那就是:
spring.jackson.deserialization.adjust-dates-to-context-time-zone=true
我正在部署到2個獨立的Ubuntu容器,一個在UTC
時區,另一個在我當前的時區America/Sao_Paulo
(GMT -3)中。
實施例有效載荷:
{"date":"2017-09-15T18:58:00.000Z"}
當服務部署在聖保羅,它接收:
2017-09-15 18:58:00.000000
哪個是正確。
當服務被部署在UTC,它接收:
2017-09-15 15:58:00.000000
這是不正確。
我使用LocalDateTime
以Java存儲日期信息。
實例模型:
import java.time.LocalDateTime;
class Model {
private LocalDateTime date;
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
}
實例資源:
@RestController
class Resource {
@RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> add(@RequestBody Model model) {
System.out.println(model.getDate());
// persistence ommited
return ResponseEntity.created(URI.create("")).build();
}
}
我不能改變我的所有生產機器的時區,我必須用傑克遜和Java(如果可能)解決這個問題。
另一個限制:不能註釋我的模型類來做到這一點。
我pom.xml
(相關部分)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.8.5</version>
</dependency>
我試過這個,但問題依然存在。我在服務器之間得到了3小時的差異(這是UTC與我的時區的差異)。 –
使用此技巧,您強制轉換UTC中的每個接收日期,以便接收的日期已準備好存儲在數據庫中。 在我的系統中我沒有使用LocalDateTime,但我使用Date和java.sql.Timestamp。 – desoss
你的答案確實有效,問題在於我的數據庫配置。謝謝。 –