0

Trying to debug an issue that is baffling me. Is there any scenario where the below code could return a string "20200931" (there are only 30 days in September). I don't think a java date can hold an invalid date no matter how it is constructed correct? I am seeing this invalid date string in a database table. The date is coming from a call to a soap service which returns a string in format "2020-09-01-05:00" and then converts it to a java.util.Date object. Finally it uses the below function to convert back into a string and writes to our database table. Regardless if the soap service returns the correct date or not I dont see how the dateFormat function can return "20200931".

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

...

    private static final DateFormat PERIOD_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

    public static String formatDate(Date dt) {
        return dt == null? "" : PERIOD_DATE_FORMAT.format(dt) ;
    }
George
  • 693
  • 7
  • 21
  • You can't have 2020-09-31. If you try to create a Date object with that value, it will fall either on October 1st or September 30th. – jrook Sep 23 '20 at 20:43
  • 2
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter.BASIC_ISO_DATE`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 24 '20 at 05:27
  • 1
    Don’t store dates as strings in your database. Use your database engine’s `date` datatype. – Ole V.V. Sep 24 '20 at 05:30
  • thanks Ole - that was the issue! – George Sep 24 '20 at 17:07

1 Answers1

1

Thanks for all the comments.

  1. I didn't write this code - its very old.
  2. Its a production issue trying to debug not new code we are writing.
  3. Its not a date we are storing but a series of dates separated with _ and used in other systems for lookups hence its a string.
  4. I know there are date objects in database.

The issue we found is that SimpleDateFormat is not thread safe and it is generating bad date strings when called repeatedly from different threads. The solution is to remove the static keyword so each instance gets its own date format object.

George
  • 693
  • 7
  • 21