kitty 23
kitty 23

Reputation: 43

Store a local year for Date

I am going to store only year value in Database and retrieve it.

This is my domain (POJO)

@Entity
public class Publisher {

public Publisher(..., Date establishDate) {
    //assign other variables
    this.setEstablishDate(establishDate);
}

    @NotNull
    private Date establishDate;
...
}

And here is my DTO:

@NotNull
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy")
private Long establish_date;

Here, i am creating a new publisher:

new Publisher(..., new Date(this.establish_date));

I sent a json with value 1370 for establish_date (for post a new publisher) , but in Database it displays as: 1970-01-01 03:30:01

Why?

And when i Get the Publisher, it displays establish_date as 1000 !

What is wrong ?

Upvotes: 0

Views: 1348

Answers (1)

J. Dow
J. Dow

Reputation: 563

You are using the wrong constructor. The argument specifies the milliseconds since 1970 - not a year: Date(long) You may use the right constructor: Date(int, int, int)

Note that most of the Date API is deprecated. There are better alternatives like Calendar and DateTime. Since you are only storing the year you could also use plain integer. This will make a lot easier.

Upvotes: 1

Related Questions