androidkotlindatetime

Why difference between timestamps gives wrong time using Date()


I don't know why, but difference between two timestamps gives wrong time as a result. Any thoughts?

                Timber.d("test delta, departed = $time1, plan = $time2")
                val deltaMills = time1.time - time2.time
                val sign = if (deltaMills < 0) "-" else if (deltaMills > 0) "+" else ""
                val pattern = if (Calendar.getInstance().fromDate(it).get(Calendar.HOUR_OF_DAY) == 0) "m" else "H:mm"
                val result = "$sign${SimpleDateFormat(pattern, Locale.getDefault()).format(Date(deltaMills.absoluteValue))}"

Logs:

test delta, departed = Fri Feb 21 14:00:01 GMT+01:00 2025, plan = Fri Feb 21 10:01:48 GMT+01:00 2025

Results

Expected: +3:58

Actual: +4:58


Solution

  • deltaMillis is a duration in milliseconds between two dates, it is not an actual date so you cannot send it into the date constructor.

    you can try the following

    Duration duration = Duration.ofMillis(millis);
    
    long h = duration.toHours();
    long m = duration.toMinutes() % 60;
    long s = duration.getSeconds() % 60;