Skip to content
Advertisement

Fetched Date is setting incorrectly

So for example I save Date to database:

@Temporal(TemporalType.DATE)
@JsonFormat(pattern="dd-MM-yyyy")
private Date arrivalDate;

And it is saved to database as this date for example 2021-09-01. Then I fetch this date and add two day for example and it should be 2021-09-03. This is the code:

Calendar c = Calendar.getInstance();
c.setTime(r.getArrivalDate()); // 2021-09-01
c.add(Calendar.DATE, r.getLivedFor()); // +2 days
residencesReportLine.setDepartDate(c.getTime());

But the result I get is not the correct I want, because I get this:

arrivalDate: 2021-08-31
departDate: 2021-09-02

is should be

arrivalDate: 2021-09-01
departDate: 2021-09-03

How I should fix this?

Advertisement

Answer

@Temporal(TemporalType.DATE)
@JsonFormat(pattern="yyyy--MM-dd")
private Date arrivalDate;


SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(r.getArrivalDate());
c.add(Calendar.DATE, 2);
String output = sdf.format(c.getTime());
residencesReportLine.setDepartDate(Timestamp.valueOf(output));
Advertisement