Search code examples
androiddatetimetimercountdowncountdowntimer

CountDown Timer not showing number of days left


I am writing a program in which i am using count down until a specific date and time, and in result i am getting countdown in hours,minutes,seconds format, but i also want to show number of days

getting this:

       Time remaining: 630 hours, 57 minutes, 25 seconds

need this:

       Time remaining: 26 days, 11 hours, 57 minutes, 25 seconds

Activity code:-

    public void onTick(long millisUntilFinished) {
                String result = ToReadableString(new org.joda.time.Period(millisUntilFinished));                   
                countdown.setText("Time remaining: " + result);
            }

    private String ToReadableString(Period period) {

        int days = period.get(DurationFieldType.days());

        int hours = period.get(DurationFieldType.hours());
        int minutes = period.getMinutes();
        int seconds = period.getSeconds();

        StringBuilder sb = new StringBuilder();

        if (days > 0) {
            sb.append(days);
            if (days == 1) {
                sb.append(" day, ");
            } else {
                sb.append(" days, ");
            }
        }

        if (hours > 0) {
            sb.append(hours);
            if (hours == 1) {
                sb.append(" hour, ");
            } else {
                sb.append(" hours, ");
            }
        }

        if (minutes > 0) {
            sb.append(minutes);
            if (minutes == 1) {
                sb.append(" minute, ");
            } else {
                sb.append(" minutes, ");
            }
        }

        if (seconds > 0) {
            sb.append(seconds);
            if (seconds == 1) {
                sb.append(" second, ");
            } else {
                sb.append(" seconds, ");
            }
        }

        String result = sb.toString().trim();

        if (result.endsWith(","))
            result = result.substring(0, result.length() - 1);

        return result;
    }
}

Solution

  • In your ToReadableString function simply do the following to obtain the number of days from the hours - you will have to work out the other differences too:

    int days = hours/24;
    hours = hours % 24;
    
    
    //rest of conversion code