Reputation: 5764
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:
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
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
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
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