Matthias
Matthias

Reputation: 5764

Android: show remaining time in human readable format

I got a timestamp (UTC) which is in the future. Now I want to show the remaining time from now on in a human readable format like "2h 15min". But I'm not sure which method of the DateUtils is the best way. Any suggestions? I was thinking of:

DateUtils.getRelativeDateTimeString

That's a sample code:

            int gmtOffset = TimeZone.getDefault().getRawOffset();
            long utcTimestamp = item.getExpirationDate();
            long localTimestamp = utcTimestamp + gmtOffset;

            Calendar c = Calendar.getInstance();
            long localNow = c.getTimeInMillis();

            // ToDo: show timespan of (localTimestamp - localNow) in human readable format e.g. 2h 5min left

Solution: That's how I solved it according to your ideas. Thanks!

    final CharSequence timespan = DateUtils.getRelativeTimeSpanString(
            localTimestamp,
            localNow,
            DateUtils.MINUTE_IN_MILLIS,
            DateUtils.FORMAT_ABBREV_RELATIVE);

Upvotes: 2

Views: 2519

Answers (3)

Aritra Roy
Aritra Roy

Reputation: 15625

The most simplest and easiest way to do this is using this,

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours   = (int) ((milliseconds / (1000*60*60)) % 24);

This is how you can get "hours", "minutes" or "seconds" from your localTimestamp - localNow

Just use,

System.out.println(hours + " hours " + minutes + " min");

This will display time in exactly the way you want. Hope it helps.

Upvotes: 1

Arshid KV
Arshid KV

Reputation: 10037

Try as following code : -

    long gmtOffset = TimeZone.getDefault().getRawOffset();
    long utcTimestamp = item.getExpirationDate();

    DateUtils.getRelativeTimeSpanString(utcTimestamp, gmtOffset, DateUtils.DAY_IN_MILLIS);

Upvotes: 3

Md Abdul Gafur
Md Abdul Gafur

Reputation: 6201

you need to do via SimpleDateFormat method. Please check the example.

Calendar cal = Calendar.getInstance();
DateFormat outputFormat = new SimpleDateFormat("hh:mm:ss a");
String formattedTime = outputFormat.format(cal.getTime());

Upvotes: 2

Related Questions