Skip to content

Instantly share code, notes, and snippets.

@jaydeepw
Created November 20, 2015 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaydeepw/895cfb65d311bf53d868 to your computer and use it in GitHub Desktop.
Save jaydeepw/895cfb65d311bf53d868 to your computer and use it in GitHub Desktop.
dat-string
/**
* Returns a string describing a day relative to the current day. For example if the day is
* today this function returns "Today", if the day was a week ago it returns "7 days ago", and
* if the day is in 2 weeks it returns "in 14 days".
*
* @param r the resources
* @param day the relative day to describe in UTC milliseconds
* @param today the current time in UTC milliseconds
*/
private static final String getRelativeDayString(Resources r, long day, long today) {
Locale locale = r.getConfiguration().locale;
if (locale == null) {
locale = Locale.getDefault();
}
// TODO: use TimeZone.getOffset instead.
Time startTime = new Time();
startTime.set(day);
int startDay = Time.getJulianDay(day, startTime.gmtoff);
Time currentTime = new Time();
currentTime.set(today);
int currentDay = Time.getJulianDay(today, currentTime.gmtoff);
int days = Math.abs(currentDay - startDay);
boolean past = (today > day);
// TODO: some locales name other days too, such as de_DE's "Vorgestern" (today - 2).
if (days == 1) {
if (past) {
return LocaleData.get(locale).yesterday;
} else {
return LocaleData.get(locale).tomorrow;
}
} else if (days == 0) {
return LocaleData.get(locale).today;
}
int resId;
if (past) {
resId = com.android.internal.R.plurals.num_days_ago;
} else {
resId = com.android.internal.R.plurals.in_num_days;
}
String format = r.getQuantityString(resId, days);
return String.format(format, days);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment