为了账号安全,请及时绑定邮箱和手机立即绑定

在实体类中选择属性的日期格式

在实体类中选择属性的日期格式

哆啦的时光机 2023-04-26 14:10:40
我正在使用Spring Data Jpa,我想要一个注释来弥补属性以选择日期格式。我寻找一些注释,但我什么也没找到。我想要这样的东西:@Entity public class User(){......(format dd/mm/aa)private Date birthDay;}
查看完整描述

3 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

您可以使用具有多种日期格式的 Spring org.springframework.format.annotation.DateTimeFormat。


在您的实体中标注您的 birthDay 属性


@Entity 

public class User(){


@DateTimeFormat(pattern="dd/MM/yyyy")

private Date birthDay;

}


查看完整回答
反对 回复 2023-04-26
?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

要说明存储到数据库中时您想要的模式,您可以使用注释@DateTimeFormat。


@Entity 

public class User {


    @DateTimeFormat("dd/MM/yyyy")

    private Date birthDay; 

}

有很多标准格式,或者您可以设置自己的自定义格式。


DateTimeFormatter.class


查看完整回答
反对 回复 2023-04-26
?
MMTTMM

TA贡献1869条经验 获得超4个赞

我相信 @DateTimeFormat 与日期(时间)在数据库中的存储方式无关 - 它与 @RequestParam 结合使用来解析 HttpRequest 参数。像那样:


@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")


查看完整回答
反对 回复 2023-04-26
  • 3 回答
  • 0 关注
  • 133 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信