Dimon
Dimon

Reputation: 454

Make timer count from Date

I am trying to make a Timer that will start counting from Date, so every time i launch the app, the Timer will always be updated for example if i start the timer at 20:00 22/11/18, tomorrow at 21:00 it will show 25:00:00.

I have only found how to do a CountdownTimer, or just a simple timer.

Upvotes: 0

Views: 201

Answers (3)

Quinn
Quinn

Reputation: 9404

You can get the current time when you start the timer with:

long timerStart = System.currentTimeMillis();

And then when you want to show what the timer is at calculate it by doing

long timePassed = System.currentTimeMillis() - timerStart;

And that will give you the number of milliseconds since you started the timer. And to format it the way you want you can pass it into this function:

public static String convertMillisToHMmSs(long millis) {
    long seconds = millis / 1000
    long s = seconds % 60;
    long m = (seconds / 60) % 60;
    long h = (seconds / (60 * 60));
    return String.format("%d:%02d:%02d", h,m,s);
}

Edit: As mentioned by the other answers, you will need to store the timerStart somewhere to keep track of it after the app is closed/reopened. I would recommend something like shared preferences you can look at this question to figure out how to do that

Upvotes: 2

Adeel Malik
Adeel Malik

Reputation: 21

Agree above with Quinn however, somewhere you need to create a file that stores the current time. Otherwise every time app restarts the variable timerStart will reset.

So you need to create a file that stores the 'timerStart' so that every time you start, it updates from the value.

Upvotes: 0

ralic
ralic

Reputation: 75

Unless you are willing to create an app that will run in background the whole time for few days (which would be highly unoptimized for an app of this complexity)

I think the best solution would be to store your start date (start timestamp) somewhere. Either in Room or in Shared Preferences and not to program your APP to increase or decrease your counter by one every second, than rather to calculate difference between start and current timestamp every second.

There are obviously a lot questions about performance but according to your question I guess that you are not concerned by this, and it will be a good practice for you to optimize this solution to be faster and more precise.

Upvotes: 0

Related Questions