TimeUtils.kt 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package eu.kanade.presentation.util
  2. import android.content.Context
  3. import android.text.format.DateUtils
  4. import androidx.compose.runtime.Composable
  5. import androidx.compose.runtime.ReadOnlyComposable
  6. import tachiyomi.core.i18n.stringResource
  7. import tachiyomi.i18n.MR
  8. import tachiyomi.presentation.core.i18n.stringResource
  9. import java.util.Date
  10. import kotlin.time.Duration
  11. import kotlin.time.Duration.Companion.minutes
  12. fun Duration.toDurationString(context: Context, fallback: String): String {
  13. return toComponents { days, hours, minutes, seconds, _ ->
  14. buildList(4) {
  15. if (days != 0L) add(context.stringResource(MR.strings.day_short, days))
  16. if (hours != 0) add(context.stringResource(MR.strings.hour_short, hours))
  17. if (minutes != 0 && (days == 0L || hours == 0)) {
  18. add(
  19. context.stringResource(MR.strings.minute_short, minutes),
  20. )
  21. }
  22. if (seconds != 0 && days == 0L && hours == 0) add(context.stringResource(MR.strings.seconds_short, seconds))
  23. }.joinToString(" ").ifBlank { fallback }
  24. }
  25. }
  26. @Composable
  27. @ReadOnlyComposable
  28. fun relativeTimeSpanString(epochMillis: Long): String {
  29. val now = Date().time
  30. return when {
  31. epochMillis <= 0L -> stringResource(MR.strings.relative_time_span_never)
  32. now - epochMillis < 1.minutes.inWholeMilliseconds -> stringResource(
  33. MR.strings.updates_last_update_info_just_now,
  34. )
  35. else -> DateUtils.getRelativeTimeSpanString(epochMillis, now, DateUtils.MINUTE_IN_MILLIS).toString()
  36. }
  37. }