简体   繁体   中英

Changing date format when sending a Response entity

We are currently using SpringBoot and PostgreSQL and we have problem with date format. When we save or edit(sending POST request from front-end) something we need a YYYY-MM-DD format since any other type of format wont save anything to database so @JSONformat on Entity or some type of annotation like that is not possible. But when we are fetching example all users it would be nicer that we get DD-MM-YYYY in a response from server, and im not sure how to do that.

We can do it from front-end but code isn't nice so back-end solution would be better.

Thanks in advance!

You can create a mapper and map your entity object to a DTO that will be sent to your front-end.

Since you don't specify the class you are using for your dates I will use LocalDate as an example, but the same logic can be applied to your date class.

Let's say your entity class looks like that:

public class SampleEntity {
    private LocalDate localDate;
}

Your DTO class will look like that:

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

Then you need to create the mapper to map from SampleEntity to SampleDto and vice versa.

@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;
    }
}

You can use all those in your controller like that:

@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);
}

With this solution, you can avoid adding Jackson annotations to your entity. Also with this solution, you can control exactly what your front-end can access. More on that here What is the use of DTO instead of Entity?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM