Java Sql使用日期(前一天)
所以我正在编写一些RESTAPI,我的一个实体有一个java.util.Date类型;我的POST端点使用JSON类型,如下所示:Java Sql使用日期(前一天),java,sql,spring,jackson,Java,Sql,Spring,Jackson,所以我正在编写一些RESTAPI,我的一个实体有一个java.util.Date类型;我的POST端点使用JSON类型,如下所示: { "authorId": 7845, "authorName": { "first": "Dan", "second": "Brown" }, "birth": { "date": "1987-10-25", "country": "USA", "city": "New York"
{
"authorId": 7845,
"authorName": {
"first": "Dan",
"second": "Brown"
},
"birth": {
"date": "1987-10-25",
"country": "USA",
"city": "New York"
},
"description": "Very good author!"
}
此外,我还重写jackson反序列化方法以处理无效的日期格式以及与此相关的所有内容:
public class CustomDateDeserializer extends StdDeserializer<LocalDate> {
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(Class t) {
super(t);
}
@Override
public Date deserialize(JsonParser jp, DeserializationContext dc) throws IOException {
String date = jp.getValueAsString();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate parsed;
try {
parsed = LocalDate.parse(date, formatter);
} catch (DateTimeParseException e) {
throw new InvalidDateTypeException(jp.currentName(), jp.getText());
}
return parsed;
}
}
在我所有中间对象(模型和DTO)的生命周期中,这个值在任何地方都像输入JSON-1987-10-25中一样
控制器:
@PostMapping(value = "/author/new", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addNewAuthor(@RequestBody @Valid AuthorPostDto postAuthor) {
AuthorPostDto response = authorService.addNewAuthor(postAuthor);
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
所有对象——postAuthor(由Jackson在Controller中解析)、toPost、response和服务返回的值——都包含类似于输入JSON-1987-10-25中的日期值
但在SQL和从控制器返回的值中,日期和前一天一起出现:1987-10-24
如何解决这个问题???可能是默认时区或偏移的问题。数据库是否以UTC格式存储日期?它是否将其存储为日期或日期时间,甚至是时间戳?@deHaar是的!我想问题就在于这个。我的时区是-2小时。java应用程序中该对象的整个生命周期的日期是1987-10-25,但并没有时间戳。当对象离开应用程序时,它将转换为1987-10-25 00:00:00。然后用我的时区。所以我得到1987-10-24 22:00:00。因为我的数据库只保存日期,所以只能得到1987-10-24。我想,它是这样工作的,那么您应该确保在Java中正确地从UTC转换为UTC,而在数据库中仅以UTC存储日期时间。
@PostMapping(value = "/author/new", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addNewAuthor(@RequestBody @Valid AuthorPostDto postAuthor) {
AuthorPostDto response = authorService.addNewAuthor(postAuthor);
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
public AuthorPostDto addNewAuthor(AuthorPostDto author) {
if (authorRepository.existsByAuthorId(author.getAuthorId())) {
throw new AuthorAlreadyExistsException();
}
Author toPost = toModelMapper.mapAuthorDtoToAuthor(author);
Author response = authorRepository.save(toPost);
return toDtoMapper.mapAuthorModelToDto_POST(response);
}