3 回答

TA貢獻1816條經(jīng)驗 獲得超6個贊
您可以使用具有多種日期格式的 Spring org.springframework.format.annotation.DateTimeFormat。
在您的實體中標注您的 birthDay 屬性
@Entity
public class User(){
@DateTimeFormat(pattern="dd/MM/yyyy")
private Date birthDay;
}

TA貢獻1795條經(jīng)驗 獲得超7個贊
要說明存儲到數(shù)據(jù)庫中時您想要的模式,您可以使用注釋@DateTimeFormat。
@Entity?
public class User {
? ? @DateTimeFormat("dd/MM/yyyy")
? ? private Date birthDay;?
}
有很多標準格式,或者您可以設(shè)置自己的自定義格式。
DateTimeFormatter.class

TA貢獻1869條經(jīng)驗 獲得超4個贊
我相信 @DateTimeFormat 與日期(時間)在數(shù)據(jù)庫中的存儲方式無關(guān) - 它與 @RequestParam 結(jié)合使用來解析 HttpRequest 參數(shù)。像那樣:
@GetMapping("/getbybirthdate")
public ResponseEntity<Page<Client>> getClientByBirthdate(@RequestParam int page, @RequestParam int size, @RequestParam @DateTimeFormat(pattern = "dd.MM.yyyy") LocalDate birthdate) {
return ResponseEntity.ok().body(clientService.getClientsByBirthdate(page, size, birthdate));
}
如果您嘗試從 java.util 包映射日期/時間類型,那么 @Temporal 是正確的選擇。如果您嘗試映射 java.time 類型,則無需顯式指定任何映射注釋,除了 @Basic 或 @Column(這是 Baeldung 建議的 - 但我相信映射不需要 @Basic 和 @Column,它們是只需要他們的額外屬性)
但是,如果問題出在將字符串值解析為日期時間,那么對于 java.time 類型,請使用
LocalDate.parse("2017-11-15")
LocalTime.parse("15:30:18")
LocalDateTime.parse("2017-11-15T08:22:12")
Instant.parse("2017-11-15T08:22:12Z")
或者對于 ISO 以外的格式,使用 DateTimeFormatter 類:
LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09"))
對于 java.util 類型:
new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15")
new SimpleDateFormat("HH:mm:ss").parse("15:30:14")
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332")
添加回答
舉報