Search code examples
androidkotlinzoneddatetime

Get plural and single from Chrono Time unit


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?


Solution

  • 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)