I want to pass the date from front-end to backend and then save to database. For front end- I am using javascript and jQuery for backend springboot, java8. When I am creating a date of this year in JavaScript
let setDate = new Date(2022, 11, 31);
console.log(setDate);
I get the output it like : Sat Dec 31 2022 00:00:00 GMT+0530 (India Standard Time)
In javascript:
reqObj.setDate = setDate;
the object in Java for this is String setDate
But when it comes to backend spring boot controller it becomes:
2022-01-30T18:30:00.000Z (day is decreased by one/ timezone changes from IST to GMT) (datatype is String in java)
After getting the String I make some formatting changes as per my need:
private String getDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy");
String resultsDate = "";
try {
resultsDate = sdf1.format(sdf.parse(date));
} catch (Exception e) {
logger.error(this.getClass().getName(), ".getDate() Exception : {}" + e);
}
return resultsDate;
}
Timezone changes resulting in date change, but the date should be the same i.e. like (2022-01-31T00:00:00.000Z)
How can I solve it from the front end?
00:00:00 GMT+0530is not same time as00:00:00.000Zsdf1.setTimeZone(TimeZone.getTimeZone("IST"));but I would also strongly recommendjava.timeas done here by T.J.CrowderSimpleDateFormatandDate. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead useInstantfrom java.time, the modern Java date and time API.