Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Android Chronometer base time from Date object?

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?

like image 900
Vitalliuss Avatar asked Jun 02 '12 13:06

Vitalliuss


2 Answers

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();
like image 60
daveespo Avatar answered Sep 21 '22 18:09

daveespo


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

SystemClock.elapsedRealtime() is the number of milliseconds since the device was turned on. The other values are based off of System.currentTimeMillis(), the number of milliseconds since the Unix epoch.

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

You don't. That is not what Chronometer is for. Quoting the documentation for Chronometer:

You can give it a start time in the elapsedRealtime() timebase, and it counts up from that, or if you don't give it a base time, it will use the time at which you call start().

like image 43
CommonsWare Avatar answered Sep 24 '22 18:09

CommonsWare