viernes, 29 de marzo de 2013

Android: Time ago...

Today I was using this very useful function from Android API for calculating time ago (added in Api Level 3) I decided to write it down here because it's a very common functionality (since I guess Facebook came up with the idea, years ago)

Code:

long minResolution = 1000;

long transitionResolution = 1000;


long ago = 1364503132624L;
String strAgo = DateUtils.getRelativeDateTimeString(
    this, ago, minResolution, transitionResolution, 0).toString();
System.out.println("How ago: " + strAgo );

This will output: 16 hours ago.

(16 will vary since the value 1364503132624L is not from 16 hours ago)

If you change the values for minResolution, you will tell Android how much or less you want to inform as minimun value. For example, if you need to report only how many hours ago has passed, then you should change this value to:

long minResolution = 60 * 60 * 1000; // 1 hour in millisecs

After doing that, you will start getting reports only when at least 1 hour has passed (before that you will get "0 hours ago")

Full documentation:
http://developer.android.com/reference/android/text/format/DateUtils.html