Search code examples
androidchronometerandroid-timer

How to make a count up timer from a specific date?


In my app user pick a date and time from a date and time picker (from the past dates) then I want to start a count up timer from that date and I need to run it in a service so that if my app killed, timer wouldn't stop. I've tried Chronometer and some similar solution on stackOverFlow but didnt get any correct solution.

Please check below picture, that It is so similar to what I need:

https://ibb.co/rFz24kg


Solution

  • For getting the difference in the dates (here, date2 can be the user-picked date and date1 can be current datetime (which you can get by calling : new Date())):

    public static String getDifferenceBetweenDates(Date date1, Date date2) {
        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;
    
        long difference = date2.getTime() - date1.getTime();
    
        long elapsedDays = difference / daysInMilli;
        difference = difference % daysInMilli;
    
        long elapsedHours = difference / hoursInMilli;
        difference = difference % hoursInMilli;
    
        long elapsedMinutes = difference / minutesInMilli;
        difference = difference % minutesInMilli;
    
        long elapsedSeconds = difference / secondsInMilli;
    
        return String.format("%s days %s hours %s minutes %s seconds", elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
    }
    

    Now once you get the difference, you can use this as a Count Up Timer and define onTick() to update your view every mCountUpInterval time interval (defined in the CountUpTimer class)