0

We have code very much like the code below where we take a java.util.Date and minus a certain amount of seconds from the date and store it as a string in a sqlite db:

private static final String DB_DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ssZ"
SimpleDateFormat DATE_FORMAT_NO_MS = new SimpleDateFormat(DB_DATE_FORMAT_STRING, Locale.US);

String dateToString(java.util.Date date date) { 
    return DATE_FORMAT_NO_MS.format(date);
}

then later we use the same string in a java 8 DateTimeFormatter to make a Java 8 OffsetDateTime:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DB_DATE_FORMAT_STRING);
OffsetDateTime odt = eventData.setDateReceived(OffsetDateTime.parse(dateString, eventDbTimeFormatter));

We keep getting crash reports like the one below when parsing the db string back into a OffsetDateTime:

2019-0005-12T12:07:47-0500' could not be parsed at index 7 org.threeten.bp.format.DateTimeFormatter.parseToBuilder

How can the month become 0005 for a SimpleDateFormat?

Jeff
  • 2,198
  • 3
  • 21
  • 38
  • Possible duplicate of [Simple Date format returns Wrong date intermittently](https://stackoverflow.com/questions/52000493/simple-date-format-returns-wrong-date-intermittently) – Ole V.V. May 14 '19 at 09:09
  • It’s a multi-threading issue. The long outmoded and notoriously troublesome `SimpleDateFormat` class is not thread-safe and will typically produce strings like the one you report when used by two or more threads simultaneously. Consider throwing it away and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. And its formatter, the `DateTimeFormatter` class, *is* thread-safe. – Ole V.V. May 14 '19 at 09:12
  • 1
    Hard to believe that `SimpleDateFormat` produces "0005" for the month part. Anyway, if you use ThreetenBP for parsing then why not also for printing (effectively replacing `SimpleDateFormat`). And then you should best get rid of `java.util.Date` at all. – Meno Hochschild May 14 '19 at 09:12
  • You should rewrite your code to add the static keyword in the line where you create an instance of `SimpleDateFormat`. Then this multithread-issue becomes clearer. – Meno Hochschild May 14 '19 at 09:14

0 Answers0