Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate elapsed time and date in android

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.

like image 707
Rujul Avatar asked Oct 16 '25 14:10

Rujul


1 Answers

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;
}
like image 135
Knossos Avatar answered Oct 18 '25 12:10

Knossos