0

I need to display in Android "1 minute ago" and "2 minutes ago" by using plurals. The problem is that I am having a map of time units with a suffix.

 val suffixes = mapOf(
        ChronoUnit.WEEKS to context.getString(R.string.time_units_week),
        ChronoUnit.DAYS to context.getString(R.string.time_units_day),
        ChronoUnit.HOURS to context.getString(R.string.time_units_hour),
        ChronoUnit.MINUTES to context.getString(R.string.time_units_minute),
        ChronoUnit.SECONDS to context.getString(R.string.time_units_second)
)

And then I am using it like this

fun timeLabel(now: ZonedDateTime): String = temporalUnits
        .map { Pair(it, targetTime.until(now, it)) }
        .find { it.second > 0 }
        ?.let { "${it.second} ${suffixes[it.first]}" }

How can I convert that so I can pass the time value to the map?

Rene Gens
  • 480
  • 6
  • 18
  • In English only? I would be surprised if the forms are built-in, but adding or removing the plural s would work for all five words (not for all English words, but I gather you don’t need that). Or you could use two maps, one for singular forms and one for plural. – Ole V.V. Jun 12 '17 at 11:12

1 Answers1

0

Found it, you can simply supply the resource itself

private val suffixes = mapOf(
        ChronoUnit.WEEKS to R.plurals.time_unit_week,
        ChronoUnit.DAYS to R.plurals.time_unit_day,
        ChronoUnit.HOURS to R.plurals.time_unit_hour,
        ChronoUnit.MINUTES to R.plurals.time_unit_minute,
        ChronoUnit.SECONDS to R.plurals.time_unit_second
)

fun timeLabel(now: ZonedDateTime): String = temporalUnits
        .map { Pair(it, targetTime.until(now, it)) }
        .find { it.second > 0 }
        ?.let {
            val pluralResources = suffixes[it.first]!!
            resources.getQuantityString(pluralResources, it.second.toInt(), it.second.toInt())
        }
        ?: context.getString(R.string.time_unit_now)
Rene Gens
  • 480
  • 6
  • 18