Home > database >  Spring-Boot jsonFormat automatically adds time to the Date field
Spring-Boot jsonFormat automatically adds time to the Date field

Time:11-22

I have a user class like this

public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer id;
    public String name;
    @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd")
    public Date date;

    public User(String name, Date date) {
        this.name = name;
        this.date = date;
    }

}

when I send the this data in request body

{
    "name":"exampleName",
    "date":"1998-07-05"
}

I recieve the input like this

name---->exampleName
date----> Sun Jul 05 05:30:00 IST 1998

( i don't want the time to be included in this field) Also, I cannot change the variable type from Date to LocaleDate

CodePudding user response:

you need to check if you send data as you wish to accept it,in controller class you need to put this to accept the data as you want `@PostMapping("/date") public void date(@RequestParam("date") @DateTimeFormat(pattern = "dd.MM.yyyy") Date date) {

}`

CodePudding user response:

Use java.time.LocalDate as the type for the date field.

Also, if you want id to be generated upon saving a User, you should annotate the class with @Entity and provide a default, no-args constructor (as well as everything else that's required to implement a persistence layer, but note that user is a reserved word in some SQL dialects).

  • Related