In my DB, I store dates as DateTime objects, so when I want to view them in UI I convert them to a predefined format which works fine. However, when I try to save new data from UI, I have to convert the string from the user back to a string that is parseable by the DB. So I came up with the following method:
private DateFormat dateFormatFromDB = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private DateFormat dateFormatFriendly = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");
private String convertFriendlyDateToDBDate(String friendlyDate){
if(friendlyDate == null){
return null;
}else{
this.dateFormatFriendly.setLenient(false);
try {
Date parsedDate = this.dateFormatFriendly.parse(friendlyDate);
String convertedDate = this.dateFormatFromDB.format(parsedDate);
System.out.println("Converted " + friendlyDate + " to " + convertedDate);
return convertedDate;
} catch (Exception error) {
System.out.println("Unable to parse the date to desired format due to the following error: " + error.getMessage());
return "error";
}
}
}
When I run the code and give it a String of 21-05-2022 19:02:08 as a parameter, I get the following in the console:
Converted 21-05-2022 19:02:08 to 2022-01-03 19:02:08.000
This is in the format I want it to, however, the date has changed from May 21st to January 3rd, any ideas on what might be causing this?