如何计算android中的经过时间和日期

时间:2016-11-07 07:41:47

标签: android date android-studio time calendar

我希望我的应用程序显示从条目存储在数据库中到从数据库中提取的时间点所经过的时间。

我目前正在做这样的事情,这让我有时间在几秒钟内完成:

                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);

但我也希望它包含自数据存储以来的天数。截至目前,它在一天结束时重置。我想让它给我N天后的总分钟数。我该怎么办?提前谢谢。

1 个答案:

答案 0 :(得分:0)

首先需要确定从数据库存储时间到现在的秒数。

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

然后,您需要确定所需的天数,然后根据该数字modulo确定剩余的毫秒数。

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;
}