How to set Android Chronometer base time from Date object?

Vitalliuss picture Vitalliuss · Jun 2, 2012 · Viewed 8.3k times · Source

I've got an issue with starting chronometer from the specific time. There is a Date object I want my chronometer start from:

Date d = new Date(); //now, just for example
chronometer.setBase(d.getTime()); //long value of d
Log.d("Date: " , "d.getTime() time is [" + d.getTime() +"]");
Log.d("Chron: " , "chronometer.getBase() is [" + chronometer.getBase() +"]");
//let's print out elapsedRealtime from official sample
Log.d("Chron: " , "SystemClock.elapsedRealtime() is [" + SystemClock.elapsedRealtime() +"]");

Output:

06-02 13:35:23.025: D/Date:(928): d.getTime() time is [1338644123032]
06-02 13:35:23.037: D/Chron:(928): chronometer.getBase() is [1338644123032]
06-02 13:35:23.037: D/Chron:(928): SystemClock.elapsedRealtime() is [11624388]

Actually, why this long values of time differes (11624388 and 1338644123032)?

When I start my chronometer from base

chronometer.setBase(SystemClock.elapsedRealtime());

- it always works fine ( "00:00" and rising)

But when I try to set the date from a past Date (f.e. yesterday):

chronometer.setBase(yesterday.getTime());

- it shows "00:0(" and changes every second the latest char to ")", "*", "/" and others

Could you please advise how can I set the chronometer base to a Date object?

Answer

daveespo picture daveespo · Nov 4, 2013

I actually had a similar problem (the Date was coming from an external service, not the database) and I wanted to show how old the date was.

It proved to be simple:

long lastSuccess = serviceDate.getTime(); //Some Date object
long elapsedRealtimeOffset = System.currentTimeMillis() - SystemClock.elapsedRealtime();
pollAgeView.setBase(lastSuccess - elapsedRealtimeOffset);
pollAgeView.start();