Skip to content

Instantly share code, notes, and snippets.

@ercnksgl
Last active September 16, 2022 08:48
Show Gist options
  • Select an option

  • Save ercnksgl/5689a99ec689dbdb6e48bfc196355d0c to your computer and use it in GitHub Desktop.

Select an option

Save ercnksgl/5689a99ec689dbdb6e48bfc196355d0c to your computer and use it in GitHub Desktop.
Relative time differences function
fun getRelativeTimeDifference(resources: Resources, time: LocalDateTime): String {
val now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
val timeDifference = now - time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
return when {
timeDifference < DateUtils.MINUTE_IN_MILLIS -> resources.getString(R.string.just_now)
timeDifference < DateUtils.HOUR_IN_MILLIS -> {
val minute = (timeDifference / DateUtils.MINUTE_IN_MILLIS).toInt()
resources.getString(R.string.minutes_ago, minute)
}
timeDifference < DateUtils.DAY_IN_MILLIS -> {
val hours = (timeDifference / DateUtils.HOUR_IN_MILLIS).toInt()
resources.getString(R.string.hours_ago, hours)
}
timeDifference < DateUtils.WEEK_IN_MILLIS -> {
val days = (timeDifference / DateUtils.DAY_IN_MILLIS).toInt()
resources.getString(R.string.days_ago, days)
}
else -> {
time.format(DateTimeFormatter.ofPattern(ApiDateFormats.MONTH_DAY_YEAR_PATTERN.format, Locale.getDefault()))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment