-2

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?

Rakib Hasan
  • 327
  • 1
  • 5
jnko
  • 157
  • 1
  • 11
  • 2
    Stop using outdated SimpleDateFormat and java.util.Date. Use the modern java.time API. – Jens May 21 '22 at 18:24
  • 3
    Change YYYY to yyyy. – Jens May 21 '22 at 18:26
  • @Jens I would however this is for an assignment which requires me to do it this way. Thanks, switching from YYYY to yyyy helped! – jnko May 21 '22 at 18:47
  • 1
    Don’t transfer your date and time as a string to or from the database. Transfer a `LocalDateTime` object. – Ole V.V. May 21 '22 at 19:06
  • You are given an assignment that requires you to use `SimpleDateFormat`, the most notoriously troublesome class? Who gives out such assignments in 2022??!! That person deserves to be sacked. The old and poor date and time classes from Java 1.0 and 1.1 were supplanted 8 years ago by java.time. – Ole V.V. May 21 '22 at 19:21
  • Your question is basically a good one IMO. For a minimal code example you need only `private DateFormat dateFormatFriendly = new SimpleDateFormat("dd-MM-YYYY HH:mm:ss");` and then `Date parsedDate = this.dateFormatFriendly.parse("21-05-2022 19:02:08");` (just hardcode the string) and of course a print statement. Leave out other lines. – Ole V.V. May 21 '22 at 19:27

0 Answers0