How to format the date time correctly in Spring Boot?

Tags: , , ,



I would like to know how to format the date time correctly? The result is Localdatetime yyyy-MM-ddTHH:mm.

Could you advise how to solve?

I’m using Java 11, and does it because @JsonFormat not support @RequestParam?

Controller:

@PostMapping("/checkFollowupDate")
public LocalDateTime updateCaseFollowup(@RequestParam("followupDate") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") LocalDateTime followupDate) {
 return followupDate;
}

Entity:

@Entity
@Table(name = "caseFollowup")
public class CaseFollowup {
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS")
    private LocalDateTime followupDate;

Answer

Since you are using Spring-boot , I’m also assuming you are using java8 . In any case try using java8 time api for date like :

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime followupDate;

and if you are on JPA 2.1 which was released before java8 then in your entity class you could have a converter to convert it for sql timestamp like :

@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
     
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
        return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
    }
 
    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
        return sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime();
    }
}

Remember that in newer version of Hibernate(Hibernate 5) and JPA the above conversion will be performed automatically and doesn’t require you to provide the above method.

If your requirement is just to persist the Date read from the @RequestParam through the entity class in a particular format, you could always convert it manually into any format that you may choose before setting the value into your entity class like :

@PostMapping("/caseFollowup")
    public Integer updateCaseFollowup(@RequestParam("followupDate")
                                       LocalDateTime followupDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = followupDate.format(formatter);

}


Source: stackoverflow