Reputation: 101
I'm using Spring Data Jpa , and I want an annontation to make it up on the attribute to choose the format of date. I look for some annotations but I don't found nothing. I want something like this :
@Entity
public class User(){
......(format dd/mm/aa)
private Date birthDay;
}
Thanks.
Upvotes: 4
Views: 34304
Reputation: 129
You can use the Spring org.springframework.format.annotation.DateTimeFormat
which has several date formats.
In your entity annotate your birthDay
property
@Entity
public class User() {
@DateTimeFormat(pattern = "dd/MM/yyyy")
private Date birthDay;
}
Upvotes: 12
Reputation: 499
I believe @DateTimeFormat has nothing to do with how the date (time) is stored in the database - it is used in combination with @RequestParam to parse HttpRequest parameters. Like that:
@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));
}
If you try to map date/time types from java.util package then @Temporal is the right choice. If you try to map java.time types then there's no need to explicitly specify any mapping annotation except for @Basic or @Column (that's what Baeldung advises to have - but I believe neither @Basic nor @Column is needed for mapping, they are needed only for their extra attributes)
BUT if the problem is in parsing of String values as date-time then in the case of java.time types please use
LocalDate.parse("2017-11-15")
LocalTime.parse("15:30:18")
LocalDateTime.parse("2017-11-15T08:22:12")
Instant.parse("2017-11-15T08:22:12Z")
or for the format other than ISO use DateTimeFormatter class:
LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09"))
and in the case of the java.util types:
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")
Upvotes: 0
Reputation: 14819
For stating what pattern you want when storing into a database you can use the @DateTimeFormat
annotation.
@Entity
public class User {
@DateTimeFormat("dd/MM/yyyy")
private Date birthDay;
}
There are a lot of standard formats or you can set your own custom format.
Upvotes: 3