4

I want my app to show the time elapsed from the point an entry was stored in the database to the point it is fetched from the database.

I am currently doing something like this which gives me time elapsed in seconds:

                SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss aa");


                Date systemDate = Calendar.getInstance().getTime();
                String myDate = sdf.format(systemDate);

                Date Date1 = sdf.parse(myDate);

                Date Date2 = sdf.parse(savedDate);
                int dateDiff = getTimeRemaining();

                long millse = Date1.getTime() - Date2.getTime();
                long mills = Math.abs(millse);                                                    
                long Mins = mills/(1000*60);

                String diff = +dateDiff+ "days " + Mins+ " mins";
                cal[1] = "" +Mins;
                t3.setText(diff);

But I also want it to include the no of days since the data was stored. As of now, it resets when the day is over. I want it to give me the total minutes after N days. How should I do it? Thanks in advance.

Rujul
  • 41
  • 1
  • 4

1 Answers1

2

You firstly need to determine the number of seconds from database-stored-time until now.

long ageOfDatabaseEntry = (System.currentTimeMillis() - databaseEnteredTimeMillis)

You then need to determine how many days you want, then modulo the age by that number to get the remaining number of milliseconds.

long getRemainingMinutes(long age, int days) {
    // Use the modulus operator to get the remainder of the age and days
    long remainder = age % (days * 86400000);

    if(remainder == age) {
        throw new InvalidArgumentException("The number of days required exceeds the age of the database entry. Handle this properly.");
    }

    // Turn the remainder in milliseconds into minutes and return it
    return remainder / 60000;
}
Knossos
  • 15,802
  • 10
  • 54
  • 91
  • Thanks! Is it a better practice to use System.currentTimeMillis() or Calendar function for such application? – Rujul Nov 07 '16 at 17:24
  • It depends on your needs. `System.currentTimeMillis()` will take the current time (as set on your device) using the _UTC_ TimeZone. That is not configurable. For most cases, this is fine. With the `Calendar`, you can add a certain amount of time or subtract, apply different TimeZones etc. – Knossos Nov 08 '16 at 08:23
  • No problem, if this helped you, don't forget to up vote and select this as your answer with the green tick. – Knossos Nov 11 '16 at 08:23