Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kerimovscreations/7acddbd30de533535f6c0c78908dbf6b to your computer and use it in GitHub Desktop.
Save kerimovscreations/7acddbd30de533535f6c0c78908dbf6b to your computer and use it in GitHub Desktop.
public static String getRelativeTimeSpanString(Context context, Date fromdate) {
long then;
then = fromdate.getTime();
Date date = new Date(then);
StringBuilder dateStr = new StringBuilder();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar now = Calendar.getInstance();
int days = daysBetween(calendar.getTime(), now.getTime());
int weeks= days/7;
int minutes = hoursBetween(calendar.getTime(), now.getTime());
int hours = minutes / 60;
if (days == 0) {
int second = minuteBetween(calendar.getTime(), now.getTime());
if (minutes > 60) {
if (hours >= 1 && hours <= 24) {
dateStr.append(String.format("%s %s %s",
hours,
context.getString(R.string.hour)
,context.getString(R.string.ago)));
}
}else {
if (second <= 10) {
dateStr.append(context.getString(R.string.now));
} else if (second <= 30) {
dateStr.append(context.getString(R.string.few_seconds_ago));
} else if (second <= 60) {
dateStr.append(String.format("%s %s %s",
second,
context.getString(R.string.seconds)
,context.getString(R.string.ago)));
} else {
dateStr.append(String.format("%s %s %s",
minutes,
context.getString(R.string.minutes)
,context.getString(R.string.ago)));
}
}
} else
if (hours > 24 && days < 7) {
dateStr.append(String.format("%s %s %s",
days,
context.getString(R.string.days)
,context.getString(R.string.ago)));
}else if(weeks == 1){
dateStr.append(String.format("%s %s %s",
weeks,
context.getString(R.string.weeks)
,context.getString(R.string.ago)));
}
else {
/**
* make formatted createTime by languageTag("fa")
*
* @return
*/
return SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG,new Locale("fra"))
.format(date).toUpperCase();
}
return dateStr.toString();
}
public static int minuteBetween(Date d1, Date d2) {
return (int) ((d2.getTime() - d1.getTime()) / android.text.format.DateUtils.SECOND_IN_MILLIS);
}
public static int hoursBetween(Date d1, Date d2) {
return (int) ((d2.getTime() - d1.getTime()) / android.text.format.DateUtils.MINUTE_IN_MILLIS);
}
public static int daysBetween(Date d1, Date d2) {
return (int) ((d2.getTime() - d1.getTime()) / android.text.format.DateUtils.DAY_IN_MILLIS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment