1

I have a function in my Android periodic worker which runs every 15 minutes:

public static final String APP_DATE_TIME_FORMAT = "dd.MM.yyyy HH:mm";
public static final SimpleDateFormat APP_DATE_TIME_FORMATTER = new SimpleDateFormat(APP_DATE_TIME_FORMAT);

public static long dayDifference(String dateInDbFormat1, String dateInDbFormat2) {
    try {
        Date date1 = APP_DATE_TIME_FORMATTER.parse(dateInDbFormat1);
        Date date2 = APP_DATE_TIME_FORMATTER.parse(dateInDbFormat2);

        long diffInMillis = Math.abs(date1.getTime() - date2.getTime());
        long diffInDays = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);

        return Math.abs(diffInDays);

    } catch (ParseException e) {
        return 0;
    }
}

That function is responsible for calculating day difference in days between two dates (SimpleDateFormat class comes from java.text package). What is really strange that I'm getting incorrect result sometimes... (for the same arguments!) And I do not know why. For example for such arguments: AppDateUtils.dayDifference("28.11.2019 00:46", "28.11.2019 01:01")) in 99% I'm getting correct result but in few cases I got below numbers: 67839, 31... instead 0 in that case.

Honestly I do not know why. What is really strange that when I put the breakpoint in my code, evaluating expression in debug mode is different than actual execution. Values in evaluated expressions are correct but actual execution sometimes works incorrectly. Also unit tests are passing without any problems for above values...

Does anyone can help me?

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
jrola
  • 219
  • 7
  • 18
  • 4
    `SimpleDateFormat` is not thread-safe. Try adding `synchronized` to your `dayDifference()` method signature. – CommonsWare Nov 30 '19 at 00:31
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, 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. – Ole V.V. Nov 30 '19 at 21:04

0 Answers0