Merge pull request #3132 from Bnyro/master

Improved relative date time formatting
This commit is contained in:
Bnyro 2023-02-20 10:17:20 +01:00 committed by GitHub
commit 1354a2908e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 2 deletions

View File

@ -142,7 +142,7 @@ class VideosAdapter(
video.views.formatShort() + " " + video.views.formatShort() + " " +
root.context.getString(R.string.views_placeholder) + root.context.getString(R.string.views_placeholder) +
TextUtils.SEPARATOR + video.uploaded?.let { TextUtils.SEPARATOR + video.uploaded?.let {
DateUtils.getRelativeTimeSpanString(it) TextUtils.formatRelativeDate(it)
} }
video.duration?.let { thumbnailDuration.setFormattedDuration(it, video.isShort) } video.duration?.let { thumbnailDuration.setFormattedDuration(it, video.isShort) }
channelImage.setOnClickListener { channelImage.setOnClickListener {
@ -174,7 +174,7 @@ class VideosAdapter(
video.views.formatShort() + " " + video.views.formatShort() + " " +
root.context.getString(R.string.views_placeholder) + root.context.getString(R.string.views_placeholder) +
TextUtils.SEPARATOR + video.uploaded?.let { TextUtils.SEPARATOR + video.uploaded?.let {
DateUtils.getRelativeTimeSpanString(it) TextUtils.formatRelativeDate(it)
} }
thumbnailDuration.text = thumbnailDuration.text =

View File

@ -1,5 +1,9 @@
package com.github.libretube.util package com.github.libretube.util
import android.icu.text.RelativeDateTimeFormatter
import android.os.Build
import android.text.format.DateUtils
import java.time.Instant
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle import java.time.format.FormatStyle
import java.util.* import java.util.*
@ -19,6 +23,10 @@ object TextUtils {
*/ */
const val RESERVED_CHARS = "?:\"*|/\\<>\u0000" const val RESERVED_CHARS = "?:\"*|/\\<>\u0000"
private const val weekInMillis: Long = 604800016
private const val monthInMillis: Long = 2629800000
private const val yearInMillis: Long = 31557600000
/** /**
* Localize the date from a time string * Localize the date from a time string
* @param date The date to parse * @param date The date to parse
@ -51,4 +59,19 @@ object TextUtils {
} }
} }
} }
fun formatRelativeDate(unixTime: Long): CharSequence {
val timeDiff = Instant.now().toEpochMilli() - unixTime
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && timeDiff > weekInMillis) {
val fmt = RelativeDateTimeFormatter.getInstance()
val (timeFormat, time) = when {
timeDiff >= yearInMillis -> RelativeDateTimeFormatter.RelativeUnit.YEARS to timeDiff / yearInMillis
timeDiff >= monthInMillis -> RelativeDateTimeFormatter.RelativeUnit.MONTHS to timeDiff / monthInMillis
else -> RelativeDateTimeFormatter.RelativeUnit.WEEKS to timeDiff / weekInMillis
}
fmt.format(time.toDouble(), RelativeDateTimeFormatter.Direction.LAST, timeFormat)
} else {
DateUtils.getRelativeTimeSpanString(unixTime)
}
}
} }