【问题标题】:Changing date format when sending a Response entity发送响应实体时更改日期格式
【发布时间】:2021-05-03 08:51:22
【问题描述】:

我们目前正在使用 SpringBoot 和 PostgreSQL,但日期格式存在问题。 当我们保存或编辑(从前端发送 POST 请求)某些内容时,我们需要 YYYY-MM-DD 格式,因为任何其他类型的格式都不会将任何内容保存到数据库中,因此实体上的 @JSONformat 或某种类型的注释是不可能的.但是当我们获取所有用户的示例时,如果我们在服务器的响应中得到 DD-MM-YYYY 会更好,我不知道该怎么做。

我们可以从前端做,但代码不是很好,所以后端解决方案会更好。

提前致谢!

【问题讨论】:

  • 如果您想要答案,您需要提供代码示例。
  • 我不是直接在 REST 响应中使用数据库实体的忠实粉丝,但 neverthelss @JSONformat 在这里应该不是问题,因为如果您使用的是 JPA(由于缺少信息而只是一个假设) 这个注解应该被 ORM 忽略,LocaleDate(我希望你使用的是 java.time 而不是 java.util.Date)应该被格式化为 Postgres 需要透明的格式。但正如灭霸所说,没有更多的上下文和理想的一些代码(阅读minimal reproducible example)很难说

标签: java spring-boot datetime


【解决方案1】:

您可以创建一个映射器并将您的实体对象映射到将发送到您的前端的 DTO。

由于您没有为您的日期指定您使用的类,我将使用LocalDate 作为示例,但可以将相同的逻辑应用于您的日期类。

假设您的实体类如下所示:

public class SampleEntity {
    private LocalDate localDate;
}

您的 DTO 类将如下所示:

public class SampleDto {
    // the Jackson annotation to format your date according to your needs.
    @DateTimeFormat(pattern = "DD-MM-YYYY")
    private LocalDate localDate;
}

然后您需要创建映射器以从 SampleEntity 映射到 SampleDto,反之亦然。

@Component
public class SampleMapper {
    public SampleDto mapTo(final SampleEntity sampleEntity){
        // do the mapping
        SampleDto sampleDto = new SampleDto();
        sampleDto.setLocalDate(sampleEntity.getLocalDate());
        return sampleDto;
    }

    public SampleEntity mapFrom(final SampleDto sampleDto){
        // do the mapping
        SampleEntity sampleEntity = new SampleEntity();
        sampleEntity.setLocalDate(sampleDto.getLocalDate());
        return sampleEntity;
    }
}

您可以像这样在控制器中使用所有这些:

@GetMapping
public ResponseEntity<SampleDto> exampleMethod() {
    // service call to fetch your entity
    SampleEntity sampleEntity = new SampleEntity(); // lets say this is the fetched entity
    sampleEntity.setLocalDate(LocalDate.now());
    SampleDto sampleDto = sampleMapper.mapTo(sampleEntity);
    return ResponseEntity.ok(sampleDto);
}

使用此解决方案,您可以避免将 Jackson 注释添加到您的实体中。同样使用此解决方案,您可以准确控制前端可以访问的内容。更多关于这里What is the use of DTO instead of Entity?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多